Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following list of Integers

(0,1,2,3)

Now I want to write a method which returns specific number of pairs from the list. So if I give it 5 as argument I will expect it to return the following:

(0,1),(1,2),(2,3),(3,0),(0,1)

So basically when it reaches the end element and another pair is needed, then it should pair the last element of the list with the first one and continue.

Any ideas how can I implement this?
Posted
Updated 19-Mar-14 2:00am
v2
Comments
Richard MacCutchan 17-Mar-14 5:58am    
Just use an iindex to select the next element and its successor. Check when the [index + 1] value is beyond the end of the list, and reset it to zero.
TorstenH. 19-Mar-14 8:00am    
Homework! PLease post code.

1 solution

You'd better try to figure it out by yourself.

C#
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] list = {0,1,2,3};
        int num = 5;
        ArrayList<int[]> results = getPairs(list, num);
        for (int[] tmp : results) {
            System.out.println("(" + tmp[0] + ","+ tmp[1] + ")");
        }

    }

    private static ArrayList<int[]> getPairs(int[] list, int num) {
        ArrayList<int[]> results = new ArrayList<int[]>();
        int len = list.length;
        int index = 0;
        for (int i = 0; i < num; i++) {
            if ((index + 1) >= len) {
                results.add(new int[]{list[index], list[0]});
                index = 0;
            }
            else {
                results.add(new int[]{list[index], list[index + 1]});
                ++index;
            }
        }
        return results;
    }
}


Here is the ouput:
(0,1)
(1,2)
(2,3)
(3,0)
(0,1)
 
Share this answer
 
Comments
TorstenH. 20-Mar-14 8:59am    
Please don't do homework for the lazy ones.
They can post code and will be helped, but we do not provide homework. common rule.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900