I'm a university student currently programming an assignment. I need to program various methods for sending and receiving messages, like for example the Hamming algorithm and Cyclic Redundancy Check.
I'm trying to program the CRC method on the transmitter end, but I can't manage to successfully program the polynomial division required. I've tried several solutions posted here, like using BitSet for division, to no avail.
Since I'm working with a graphical interface, designed in NetBeans 8.0.1, my question is: how can I manipulate Strings coming from several jTextFields to generate a binary message with the CRC algorithm?
Note: this is the first time I'm using Stack Overflow, so if I'm missing anything, please point it out for me. Thanks in advance.
EDIT: As requested, here is my sample code using BitSet: (note: some variable names are in Spanish since I'm a native Spanish-speaker)
public static String CRC(String m, String G){
BitSet dividendo, divisor, divid1, divid2, resto, blanco;
dividendo = new BitSet(m.length());
divisor = new BitSet(G.length());
blanco = new BitSet(G.length());
blanco.clear();
for (int i = 0; i < m.length(); i++){
if(Integer.parseInt(m.substring(i, i+1)) == 1) {
dividendo.set(i);
} else {
dividendo.clear(i);
}
}
for (int i = 0; i < G.length(); i++){
if(Integer.parseInt(G.substring(i, i+1)) == 1) {
divisor.set(i);
} else {
divisor.clear(i);
}
}
divid1 = dividendo.get(0, divisor.length());
int largo1, largo2, largo3, largo4;
largo1 = dividendo.length();
largo2 = divisor.length();
largo3 = blanco.length();
largo4 = divid1.length();
for (int i = divisor.length(); i < dividendo.length(); i++) {
if (divid1.get(0) == divisor.get(0)){
divid1.xor(divisor);
divid2 = new BitSet(divid1.length());
for (int j = 1; j<divid1.length(); j++){
if(divid1.get(j))
divid2.set(j-1);
else
divid2.clear(j-1);
}
boolean valor = dividendo.get(i);
int largo5 = divid2.length();
divid2.set(divid2.length(), valor);
divid1 = divid2;
} else {
divid1.xor(blanco);
divid2 = new BitSet(divid1.length());
for (int j = 1; j<divid1.length(); j++){
if(divid1.get(j))
divid2.set(j);
else
divid2.clear(j);
}
boolean valor = dividendo.get(i);
divid2.set(divid2.length(), valor);
divid1 = divid2;
}
}
resto = new BitSet(divid1.length());
for (int j = 1; j<divid1.length(); j++){
if(divid1.get(j))
resto.set(j);
else
resto.clear(j);
}
String mFinal = dividendo.toString() + resto.toString();
return mFinal;
}
With inputs
String m = "10010101"
String G = "1011"
my expected output vs. actual output was
expected = 10010101010
actual = {0, 3, 5, 7}{1, 2, 3} (first array is the original message, second is the appended remainder)
with the code mentioned above.
I'm at a loss on what I'm doing wrong, so any kind of help will be appreciated.
CRCs are not calculated by doing polynomial divisions term-by-term. Polynomials over GF(2) and their division are how CRCs are defined and analyzed mathematically. The actual calculation is done with binary representations of the polynomials and states stored in machine integers, using rotations and exclusive-ors to operate on all the terms of the polynomials in parallel.
I recommend Ross Williams' tutorial on CRCs for a description of how you go from polynomials over GF(2) to exclusive-ors and rotates of binary strings.
Related
This question already has answers here:
nᵗʰ ugly number
(13 answers)
Closed 2 years ago.
I am trying to solve the LeetCode ugly number challenge II. I came up with an algorithm of my own, seems working in theory but does not. I want to know why. I implemented this in Java but I write in Python normally, so if you correct the Java code, would appreciate.
The problem statement is:
"Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2,
3, 5.
Example:
Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10 ugly numbers. Note:
1 is typically treated as an ugly number. n does not exceed 1690."
This is my code:
class Solution {
public int nthUglyNumber(int n) {
// Gather all the uglies in one place
int[] uglies = new int[n];
// Set first one as one
uglies[0] = 1;
// Start filling
for (int i = 1; i < uglies.length - 1; i++) {
int num = i;
if (isUgly(num) == true) {
uglies[i] = num;
} else {
while (isUgly(num) == false) {
num++;
}
uglies[i] = num;
System.out.println(uglies[i]);
}
}
return uglies[uglies.length - 1];
}
public boolean isUgly(int m) {
boolean ans = false;
// Check if the number is divisible by an integer other than 2,3 or 5
// Simply iterate through numbers smaller than n to find a smaller divisor
for (int i = 2; i < m; i++) {
// If n is divisable by i and i is not a multiple of 2,3 or 5
boolean other_divisor = (m % i == 0) && (i % 2 != 0 || i % 3 != 0 || i % 5 != 0);
if (other_divisor == true) {
ans = false;
} else {
ans = true;
}
}
return ans;
}
}
So I basically made a function isUgly(n), which takes a number and checks if it is ugly by finding out if it has a divisor other than 2,3,5. If there is, then it should not be an ugly number. Than in the main body I go over all integers and check if they are ugly. If they are, I add them to an array until I fill out the n-th position. Would appreciate if corrected.
Not sure where your bug is. But, it has to be solved efficiently (time and space).
These solutions would pass through LeetCode, yet are not the most efficient algorithms for the problem. Since the question is math related, pretty sure there are many ways to make it much efficient.
C++
#include <vector>
class Solution {
public:
int nthUglyNumber(int n) {
int factor_two = 0;
int factor_three = 0;
int factor_five = 0;
std::vector<int> uglies(n);
uglies[0] = 1;
for (int index = 1; index < n; index++) {
uglies[index] = std::min(uglies[factor_five] * 5, std::min(uglies[factor_two] * 2, uglies[factor_three] * 3));
if (uglies[index] == uglies[factor_two] * 2) {
factor_two++;
}
if (uglies[index] == uglies[factor_three] * 3) {
factor_three++;
}
if (uglies[index] == uglies[factor_five] * 5) {
factor_five++;
}
}
return uglies[n - 1];
}
};
Java
public class Solution {
public int nthUglyNumber(int n) {
int[] uglies = new int[n];
uglies[0] = 1;
int indexTwo = 0;
int indexThree = 0;
int indexFive = 0;
int two = 2;
int three = 3;
int five = 5;
for (int index = 1; index < n; index++) {
int minFactor = Math.min(five, Math.min(two, three));
uglies[index] = minFactor;
if (minFactor == two) {
two = 2 * uglies[++indexTwo];
}
if (minFactor == three) {
three = 3 * uglies[++indexThree];
}
if (minFactor == five) {
five = 5 * uglies[++indexFive];
}
}
return uglies[n - 1];
}
}
Python
class Solution:
def nthUglyNumber(self, n: int) -> int:
uglies = (1,)
factor_two = factor_three = factor_five = 0
while len(uglies) < n:
while uglies[factor_two] * 2 <= uglies[-1]:
factor_two += 1
while uglies[factor_three] * 3 <= uglies[-1]:
factor_three += 1
while uglies[factor_five] * 5 <= uglies[-1]:
factor_five += 1
curr_ugly = min(uglies[factor_two] * 2, uglies[factor_three] * 3, uglies[factor_five] * 5)
uglies += (curr_ugly,)
return uglies[-1]
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
If you are preparing for interviews:
We would want to write bug-free and clean codes based on standards and conventions (e.g., c1, 2, c++1, 2, java1, 2, c#1, 2, python1, javascript1, go1, rust1). Overall, we would like to avoid anything that might become controversial for interviews.
There are also other similar platforms, which you might have to become familiar with, in case you'd be interviewing with specific companies that would use those platforms.
If you are practicing for contests1:
Just code as fast as you can, almost everything else is very trivial.
For easy questions, brute force algorithms usually get accepted. For interviews, brute force is less desired, especially if the question would be an easy level.
For medium and hard questions, about 90% of the time, brute force algorithms fail mostly with Time Limit Exceeded (TLE) and less with Memory Limit Exceeded (MLE) errors.
Contestants are ranked based on an algorithm explained here.
I'm a first-year computer science student and I am currently dabbling in some algorithmic competitions. The code below that I made has a flaw that I'm not sure how to fix
Here is the problem statement:
http://www.usaco.org/index.php?page=viewproblem2&cpid=811
In the statement, I missed where it said that Farmer John could only switch boots on tiles that both boots can stand on. I tried adding constraints in different places but none seemed to address the problem fully. I don't really see a way to do it without butchering the code
Basically, the problem is that John keeps switching boots on tiles where the new boots can't stand on, and I can't seem to fix it
Here is my code (sorry for the one letter variables):
import java.io.*;
import java.util.*;
public class snowboots {
static int n,k;
static int[] field,a,b; //a,b --> strength, distance
static int pos;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("snowboots.in"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("snowboots.out")));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
field = new int[n];
a = new int[k];
b = new int[k];
for (int i = 0; i < n; i++)
field[i] = Integer.parseInt(st.nextToken());
for (int i = 0; i < k; i++) {
st = new StringTokenizer(br.readLine());
a[i] = Integer.parseInt(st.nextToken());
b[i] = Integer.parseInt(st.nextToken());
}
pw.println(solve());
pw.close();
}
static int solve() {
pos = 0;
int i = 0; //which boot are we on?
while(pos < n-1) {
while(move(i)); //move with boot i as far as possible
i++; //use the next boot
}
i--;
return i;
}
static boolean move(int c) {
for (int i = pos+b[c]; i > pos; i--) {
if (i < n && field[i] <= a[c]) { //snow has to be less than boot strength
pos = i;
return true;
}
}
return false;
}
}
I tried adding a constraint in the "move" method, and one when updating I, but they both are too strict and activate at unwanted times
Is it salvageable?
Yes, it's possible to salvage your solution, by adding an extra for-loop.
What you need to do is, if you find that your previous pair of boots can get you all the way to a tile that's too deep in snow for your next pair, then you need to try "backtracking" to the latest tile that's not too deep. This ends up giving a solution in worst-case O(N·B) time and O(1) extra space.
It may not be obvious why it's OK to backtrack to that tile — after all, just because you can reach a given tile, that doesn't necessarily mean that you were able to reach all the tiles before it — so let me explain a bit why it is OK.
Let maxReachableTileNum be the number (between 1 and N) of the last tile that you were able to reach with your previous boots, and let lastTileNumThatsNotTooDeep be the number (between 1 and N) of the last tile on or before maxReachableTileNum that's not too deeply snow-covered for your next pair. (We know that there is such a tile, because tile #1 has no snow at all, so if nothing else we know that we can backtrack to the very beginning.) Now, since we were able to get to maxReachableTileNum, then some previous boot must have either stepped on lastTileNumThatsNotTooDeep (in which case, no problem, it's reachable) or skipped over it to some later tile (on or before maxReachableTileNum). But that later tile must be deeper than lastTileNumThatsNotTooDeep (because that later tile's depth is greater than scurrentBootNum, which is at least at great as the depth of lastTileNumThatsNotTooDeep), which means that the boot that skipped over lastTileNumThatsNotTooDeep certainly could have stepped on lastTileNumThatsNotTooDeep instead: it would have meant taking a shorter step (OK) onto a less-deeply-covered tile (OK) than what it actually did. So, either way, we know that lastTileNumThatsNotTooDeep was reachable. So it's safe for us to try backtracking to lastTileNumThatsNotTooDeep. (Note: the below code uses the name reachableTileNum instead of lastTileNumThatsNotTooDeep, because it continues to use the reachableTileNum variable for searching forward to find reachable tiles.)
However, we still have to hold onto the previous maxReachableTileNum: backtracking might turn out not to be helpful (because it may not let us make any further forward progress than we already have), in which case we'll just discard these boots, and move on to the next pair, with maxReachableTileNum at its previous value.
So, overall, we have this:
public static int solve(
final int[] tileSnowDepths, // tileSnowDepths[0] is f_1
final int[] bootAllowedDepths, // bootAllowedDepths[0] is s_1
final int[] bootAllowedTilesPerStep // bootAllowedTilesPerStep[0] is d_1
) {
final int numTiles = tileSnowDepths.length;
final int numBoots = bootAllowedDepths.length;
assert numBoots == bootAllowedTilesPerStep.length;
int maxReachableTileNum = 1; // can reach tile #1 even without boots
for (int bootNum = 1; bootNum <= numBoots; ++bootNum) {
final int allowedDepth = bootAllowedDepths[bootNum-1];
final int allowedTilesPerStep = bootAllowedTilesPerStep[bootNum-1];
// Find the starting-point for this boot -- ideally the last tile
// reachable so far, but may need to "backtrack" if that tile is too
// deep; see explanation above of why it's safe to assume that we
// can backtrack to the latest not-too-deep tile:
int reachableTileNum = maxReachableTileNum;
while (tileSnowDepths[reachableTileNum-1] > allowedDepth) {
--reachableTileNum;
}
// Now see how far we can go, updating both maxReachableTileNum and
// reachableTileNum when we successfully reach new tiles:
for (int tileNumToTry = maxReachableTileNum + 1;
tileNumToTry <= numTiles
&& tileNumToTry <= reachableTileNum + allowedTilesPerStep;
++tileNumToTry
) {
if (tileSnowDepths[tileNumToTry-1] <= allowedDepth) {
maxReachableTileNum = reachableTileNum = tileNumToTry;
}
}
// If we've made it to the last tile, then yay, we're done:
if (maxReachableTileNum == numTiles) {
return bootNum - 1; // had to discard this many boots to get here
}
}
throw new IllegalArgumentException("Couldn't reach last tile with any boot");
}
(I tested this on USACO's example data, and it returned 2, as expected.)
This can potentially be optimized further, e.g. with logic to skip pairs of boots that clearly aren't helpful (because they're neither stronger nor more agile than the previous successful pair), or with an extra data structure to keep track of the positions of latest minima (to optimize the backtracking process), or with logic to avoid backtracking further than is conceivably useful; but given that N·B ≤ 2502 = 62,500, I don't think any such optimizations are warranted.
Edited to add (2019-02-23): I've thought about this further, and it occurs to me that it's actually possible to write a solution in worst-case O(N + B log N) time (which is asymptotically better than O(N·B)) and O(N) extra space. But it's much more complicated; it involves three extra data-structures (one to keep track of the positions of latest minima, to allow backtracking in O(log N) time; one to keep track of the positions of future minima, to allow checking in O(log N) time if the backtracking is actually helpful (and if so to move forward to the relevant minimum); and one to maintain the necessary forward-looking information in order to let the second one be maintained in amortized O(1) time). It's also complicated to explain why that solution is guaranteed to be within O(N + B log N) time (because it involves a lot of amortized analysis, and making a minor change that might seem like an optimization — e.g., replacing a linear search with a binary search — can break the analysis and actually increase the worst-case time complexity. Since N and B are both known to be at most 250, I don't think all the complication is worth it.
You can solve this problem by Dynamic Programming. You can see the concept in this link (Just read the Computer programming part).
It has following two steps.
First solve the problem recursively.
Memoize the states.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mx 100005
#define mod 1000000007
int n, b;
int f[333], s[333], d[333];
int dp[251][251];
int rec(int snowPos, int bootPos)
{
if(snowPos == n-1){
return 0;
int &ret = dp[snowPos][bootPos];
if(ret != -1) return ret;
ret = 1000000007;
for(int i = bootPos+1; i<b; i++)
{
if(s[i] >= f[snowPos]){
ret = min(ret, i - bootPos + rec(snowPos, i));
}
}
for(int i = 1; i<=d[bootPos] && snowPos+i < n; i++){
if(f[snowPos + i] <= s[bootPos]){
ret = min(ret, rec(snowPos+i, bootPos));
}
}
return ret;
}
int main()
{
freopen("snowboots.in", "r", stdin);
freopen("snowboots.out", "w", stdout);
scanf("%d %d", &n, &b);
for(int i = 0; i<n; i++)
scanf("%d", &f[i]);
for(int i = 0; i<b; i++){
scanf("%d %d", &s[i], &d[i]);
}
memset(dp, -1, sizeof dp);
printf("%d\n", rec(0, 0));
return 0;
}
This is my solution to this problem (in C++).
This is just a recursion. As problem says,
you can change boot, Or
you can do a jump by current boot.
Memoization part is done by the 2-Dimensional array dp[][].
One way which to solve it using BFS. You may refer below code for details. Hope this helps.
import java.util.*;
import java.io.*;
public class SnowBoots {
public static int n;
public static int[] deep;
public static int nBoots;
public static Boot[] boots;
public static void main(String[] args) throws Exception {
// Read the grid.
Scanner stdin = new Scanner(new File("snowboots.in"));
// Read in all of the input.
n = stdin.nextInt();
nBoots = stdin.nextInt();
deep = new int[n];
for (int i = 0; i < n; ++i) {
deep[i] = stdin.nextInt();
}
boots = new Boot[nBoots];
for (int i = 0; i < nBoots; ++i) {
int d = stdin.nextInt();
int s = stdin.nextInt();
boots[i] = new boot(d, s);
}
PrintWriter out = new PrintWriter(new FileWriter("snowboots.out"));
out.println(bfs());
out.close();
stdin.close();
}
// Breadth First Search Algorithm [https://en.wikipedia.org/wiki/Breadth-first_search]
public static int bfs() {
// These are all valid states.
boolean[][] used = new boolean[n][nBoots];
Arrays.fill(used[0], true);
// Put each of these states into the queue.
LinkedList<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < nBoots; ++i) {
q.offer(i);
}
// Usual bfs.
while (q.size() > 0) {
int cur = q.poll();
int step = cur / nBoots;
int bNum = cur % nBoots;
// Try stepping with this boot...
for (int i = 1; ((step + i) < n) && (i <= boots[bNum].maxStep); ++i) {
if ((deep[step+i] <= boots[bNum].depth) && !used[step+i][bNum]) {
q.offer(nBoots * (step + i) + bNum);
used[step + i][bNum] = true;
}
}
// Try switching to another boot.
for (int i = bNum + 1; i < nBoots; ++i) {
if ((boots[i].depth >= deep[step]) && !used[step][i]) {
q.offer(nBoots * step + i);
used[step][i] = true;
}
}
}
// Find the earliest boot that got us here.
for (int i = 0; i < nBoots; ++i) {
if (used[n - 1][i]) {
return i;
}
}
// Should never get here.
return -1;
}
}
class Boot {
public int depth;
public int maxStep;
public Boot(int depth, int maxStep) {
this.depth = depth;
this.maxStep = maxStep;
}
}
I've been reading documentation about String.hashCode() on
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java
Trying obtain an identical result from an identical string, but I did not come up with any satisfying results.
In Objective-C [NSString hash] gives a totally different result.
Have anyone already done this?
Thanks
The answer provided by Alfred is not correct. First of all, hashCode can return negative, so the return type should be a signed integer and not an unsigned integer. Secondly, the charAsciiValue++ is off. In the original Java code, an array index is being incremented, not a unichar. Here is a tested/working version that's a category on NSString:
- (int)javaHashCode
{
int h = 0;
for (int i = 0; i < (int)self.length; i++) {
h = (31 * h) + [self characterAtIndex:i];
}
return h;
}
Edit: I originally used NSInteger, but I ran into issues with it. I believe it was due to the machine being 64 bit. Switching NSInteger to int fixed my issue.
Updated code for swift 4
func javaHashCode(name:String)-> Int{
var nsname = name as! NSString; var h:Int = 0
for (index,value) in name.enumerated(){
h = 31*h + Int(nsname.character(at:index))
}
return h
}
I made an efficient snippet that mimic the Java string.hashCode() result using the math algorithm at the wiki page:
http://en.wikipedia.org/wiki/Java_hashCode%28%29#The_java.lang.String_hash_function
+ (NSUInteger) hashCodeJavaLike:(NSString *)string {
int h = 0;
int len = string.length;
for (int i = 0; i < len; i++) {
//this get the ascii value of the character at position
unichar charAsciiValue = [string characterAtIndex: i];
//product sum algorithm over the entire text of the string
//http://en.wikipedia.org/wiki/Java_hashCode%28%29#The_java.lang.String_hash_function
h = 31*h + (charAsciiValue++);
}
return h;
}
hope it help someone!
Keep in mind, as commented by Chris, that if the Java string.hashCode() algorithm is rewritten problems may occur.
I am trying to simulate the math puzzle I found on http://blog.xkcd.com/2010/02/09/math-puzzle/. However, the java random class is returning weird results. In the code below, the result is what is expected. The output is somewhere around .612 for the first line and between .49 and .51 for the second.
int trials = 10000000;
int success = 0;
int returnstrue = 0;
for (int i = 0; i < trials; i++) {
Random r = new Random();
//double one = r.nextDouble()*10000;
//double two = r.nextDouble()*10000;
double one = 1;
double two = Math.PI;
double check = r.nextDouble();
boolean a = r.nextBoolean();
if(a)
{
returnstrue++;
}
if(a){
if((check>p(one)) && two > one)
{
success++;
}
if((check<p(one))&& two<one)
{
success++;
}
}
else{
if((check>p(two)) && two < one)
{
success++;
}
if((check<p(two))&& two>one)
{
success++;
}
}
}
System.out.println(success/(double)trials);
System.out.println(returnstrue/(double)trials);
However, when I switch the lines of
double check = r.nextDouble();
boolean a = r.nextBoolean();
to
boolean a = r.nextBoolean();
double check = r.nextDouble();
the output is around .476 for the first number and .710 for the second. This implies that the nextBoolean() method is returning true 70% of the time in the later configuration. Am I doing something wrong or is this just a bug?
Move the instantiation of r to outside the for loop, as in:
Random r = new Random();
for (int i = 0; i < trials; i++) {
:
}
What you are doing now is creating a new one every time the loop iterates and, since the seed is based on the time (milliseconds), you're likely to get quite a few with the same seed.
That's almost certainly what's skewing your results.
So, yes, it is a bug, just in your code rather than in Java. That tends to be the case in about 99.9999% of the times when people ask that question since Java itself is continuously being tested by millions around the world and that snippet of yours has been tested by, well, just you :-)
I have an input signal that I want to store in an ArrayList then convert it into Complex, which goes something like this
-0.03480425839330703
0.07910192950176387
0.7233322451735928
0.1659819820667019
and this outputs its FFT like this
0.9336118983487516
-0.7581365035668999 + 0.08688005256493803i
0.44344407521182005
-0.7581365035668999 - 0.08688005256493803i
This is in a complex structure, I want to convert this into an ArrayList type. while dropping the + 0.08688005256493803i value.
So All I need are these values
0.9336118983487516
-0.7581365035668999
0.44344407521182005
-0.7581365035668999
What is the best way of going about this?
And this is the code that I am using
public static Complex[] fft(Complex[] x) {
int N = x.length;
// base case
if (N == 1) return new Complex[] { x[0] };
// radix 2 Cooley-Tukey FFT
if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); }
// fft of even terms
Complex[] even = new Complex[N/2];
for (int k = 0; k < N/2; k++) {
even[k] = x[2*k];
}
Complex[] q = fft(even);
// fft of odd terms
Complex[] odd = even; // reuse the array
for (int k = 0; k < N/2; k++) {
odd[k] = x[2*k + 1];
}
Complex[] r = fft(odd);
// combine
Complex[] y = new Complex[N];
for (int k = 0; k < N/2; k++) {
double kth = -2 * k * Math.PI / N;
Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
y[k] = q[k].plus(wk.times(r[k]));
y[k + N/2] = q[k].minus(wk.times(r[k]));
}
return y;
}
All you want to do is just drop imaginary part of your Complex data structure.
As you not show us Complex class assume it has member for real part (e.g double real;)
To drop imaginary part just call something like complex.getRealPart(), or access complex.real (substitute with your real member name).
To compose ArrayList<Double> use the following snippet:
ArrayList<Double> list = new ArrayList<Double>();
for (Complex c : complexes) { // complexes your array of complexes returned from for fft
list.add(c.getRealpart());
}
Note: Just in case, I can be wrong, but I assume that instead of real part you need absolute value of complex number. To calculate it use:
Math.sqrt(c.getRealPart() * c.getRealPart() + c.getImPart() * c.getImPart());
From what I understand you just want the real part of the complex value. If that's the case, presumably your Complex class also has getReal() and getImaginary() (or similar) methods - so just use getReal().