-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBooksExchange.java
More file actions
51 lines (42 loc) · 1.25 KB
/
BooksExchange.java
File metadata and controls
51 lines (42 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class BooksExchange
{
public static void main( String[] args )
{
Scanner scanner = new Scanner( System.in );
int t = Integer.parseInt( scanner.nextLine() );
ArrayList<Integer[]> res = new ArrayList<Integer[]>();
while(t-->0)
{
int numberOfKids =Integer.parseInt( scanner.nextLine()) ;
String[] kidsStr = scanner.nextLine().split(" " );
int[] kids = Arrays.asList( kidsStr ).stream().mapToInt( Integer::parseInt ).toArray();
res.add( getNoOfExchanges( kids ) );;
}
for(Integer[] exchanges: res)
{
for(Integer ex: exchanges)
{
System.out.println( ex );
}
}
}
private static Integer[] getNoOfExchanges( int[] kids )
{
Integer[] res = new Integer[kids.length];
for(int i=0;i<kids.length;i++)
{
int index=1;
int nextIndex = kids[i];
while((i+1)!=nextIndex)
{
nextIndex = kids[nextIndex];
index++;
}
res[i] = index;
}
return res;
}
}