Reputation: 6139
[A, B, C, D, E, F]
I need to get adjacent values from above array.
Adjacent count can vary say
if adjcnt = 2
Then I should get like this
tuple 1 = A,B
tuple 2 = C,D
tuple 3 = E,F
If adjcnt = 3
tuple 1 = A,B,c
tuple 2 = D,E,F
My code
for (int i = 0; i < arr.length; i++) {
if(i < adjcnt){
if(i==0){
csv = arr[i];
}
else{
csv += ","+arr[i];
}
}
System.out.println("csv---> "+csv);
}
This prints only 2 elements. I need to loop till my arr is empty
Some where my logic is not right. Please Advice
Upvotes: 1
Views: 259
Reputation: 2052
Unmesha, you can use the following code for your expected output
public class Adjacent {
public static void main(String args[]) {
char[] test = { 'a', 'b', 'c', 'd', 'e', 'f' };
int adjcnt = 3;
StringBuilder csv = new StringBuilder();
int tuplecount = 1;
for (int i = 0; i < test.length; i++) {
if (i % adjcnt == 0 || i == 0) {
if (i != 0)
csv.append("\n");
csv.append("tuple ");
csv.append(tuplecount);
csv.append("=");
csv.append(test[i]);
} else {
csv.append(",");
csv.append(test[i]);
}
}
System.out.println(csv.toString());
}
}
Please update me if this code works out for you
Upvotes: 0
Reputation: 35577
You can try this way too.
int adjcnt = 3;
String[] arr = {"A", "B", "C", "D", "E", "F"};
for(int i=0; i< arr.length; i= i + adjcnt){
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, i, i+adjcnt)));
//here it will copy your original array between given indexes.
}
out put:
[A, B, C]
[D, E, F]
Upvotes: 0
Reputation: 261
#include<stdio.h>
int main()
{
int arr[6] = {1,2,3,4,5,6};
int i = 0;
int adjacent = 2;
for(i=0;i<6;i++)
{
if( i% adjacent == 0 ) {
printf("\n");
}
printf("%d",arr[i]);
}
return 0;
}
Upvotes: 0
Reputation: 2770
Change your this code:-
for (int i = 0; i < arr.length; i++) {
if(i < adjcnt){
if(i==0){
csv = arr[i];
}
else{
csv += ","+arr[i];
}
}
System.out.println("csv---> "+csv);
}
to the following
for (int i = 0; i < arr.length; i++) {
if((i % adjcnt) < adjcnt){
if((i % adjcnt)==0){
csv = arr[i];
}
else{
csv += ","+arr[i];
}
}
System.out.println("csv---> "+csv);
}
Upvotes: 2