Reputation: 1005
I am writing a program on signal processing. An example of appearance of signals is below:
Two arrays: having corresponding elements. Always they have equal number of elements as:
String signal[] = {"x", "y", "y" "C", "C", "z","C","C","x","C"};
int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };
In the, signal [], x, y, and z are the names of three signals. C tells their continuation. in the times[] , integers shows the the time for which a signal appeared for current first time, under the C figure tells for which the signal continued for additional time. The math logic goes as:
the time of x =2, (=2)
the time of y = 5 (=5)
the time of y = 1+4+7 (=12)
the time of z = 8 +2+6 (=16)
the time of x = 4+3 (=7)
I need the output as {x=2, y=5, y=12, z=16, x=7}
What should I do to relate the elements of the arrays to get this output?
Upvotes: 0
Views: 125
Reputation: 1315
This is a very bad implementation, but if you have no other choice than formatting your input as you provided, this is the best I can do:
public static void main(String[] args)
{
String signal[] = {"x", "y", "y", "C", "C", "z","C","C","x","C"};
int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };
int i=0;
while (i < signal.length)
{
switch(signal[i])
{
case "x":
{
System.out.print("x = ");
int sum = time[i];
if(signal[i+1] == "C")
{
i++;
while(i < signal.length && signal[i] == "C" )
{
sum += time[i];
i++;
}
}
else i++;
System.out.print(sum + " ");
break;
}
case "y":
{
System.out.print("y = ");
int sum = time[i];
if(signal[i+1] == "C")
{
i++;
while(i < signal.length && signal[i] == "C" )
{
sum += time[i];
i++;
}
}
else i++;
System.out.print(sum + " ");
break;
}
case "z":
{
System.out.print("z = ");
int sum = time[i];
if(signal[i+1] == "C")
{
i++;
while(i < signal.length && signal[i] == "C" )
{
sum += time[i];
i++;
}
}
else i++;
System.out.print(sum + " ");
break;
}
}
}
}
Output: x = 2 y = 5 y = 12 z = 16 x = 7
Upvotes: 1
Reputation: 3771
package com.company;
public class Main {
public static void main(String[] args) {
String signal[] = new String[]{"x", "y", "y", "C", "C", "z", "C", "C", "x", "C"};
int time[] = new int[]{2, 5, 1, 4, 7, 8, 2, 6, 4, 3};
int index = 0;
while (index < time.length) {
int sum = time[index];
String sig = signal[index];
while ((index < (signal.length - 1) && signal[index + 1].equals("C"))) {
sum = sum + time[index + 1];
index++;
}
System.out.println(sig + " " + sum);
index++;
}
}
}
Upvotes: 1
Reputation: 66
This is precisely the reason java has a class system. Why not create a signal class with necessary information for each signal rather than trying to keep a bunch of arrays in tune with each other. Or use a Map as suggested?
Upvotes: 4