0

i want correct anwer code

import java.util.*; public class SockPair { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Read number of socks int n = sc.nextInt(); int[] ar = new int[n]; // Read sock colors for (int i=0;i< n;i++) { ar[i] = sc.nextInt(); } // Count occurrences int[] count = new int[101]; for (int i=0;i<n;i++) { count[ar[i]]++; } // Calculate pairs int answer = 0; for (int i=0; i<101;i++) { answer += count[i] / 2; } System.out.println("Number of pairs: " + answer); } }

18th Jul 2025, 11:57 AM
Zoyafathima
Zoyafathima - avatar
4 Answers
0
Zoyafathima Your code is correctly counting the pairs of number. What problem are you facing in your code, can you briefly describe your problem? You may have problem with input, so your input must be like this:- 4 6 5 4 5 Or 4 6 5 4 5 Output:- 1
18th Jul 2025, 12:37 PM
Gulshan Mahawar
Gulshan Mahawar - avatar
0
The code is correct, you just need to enter manual values. Input { 4 // inserted that I have four pairs of socks 1 2 1 2 // Colors are represented as numbers } The program will join them in the vector and read the equal values and divide them into pairs Color 1-> 2 socks --> 2/2 = 1 pair Color 2-> 2 socks --> 2/2 = 1 pair In the end, he adds up the pairs 1 pair color 1 + 1 pair color 2 = 2 Output { Number of pairs: 2 }
18th Jul 2025, 12:45 PM
Zero
Zero - avatar
0
Sometimes it can give an error because the Scanner is not importing, but I think it's unlikely to be that :/ maybe it's an input error
18th Jul 2025, 12:46 PM
Zero
Zero - avatar
0
Damn bro went straight for the point
18th Jul 2025, 1:04 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar