Skip to main content
Code Review

Return to Question

Commonmark migration
Source Link

Challenge

###Challenge GivenGiven a list of numbers and a positive integer k, reverse the elements of the list, k items at a time.

###Specifications

Specifications

###Challenge Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time.

###Specifications

Challenge

Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time.

Specifications

edited title
Link
200_success
  • 145.5k
  • 22
  • 190
  • 478

Numeral reversal Reverse each group of k elements in a list

Source Link
Legato
  • 9.9k
  • 4
  • 50
  • 118

Numeral reversal

###Challenge Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time.

###Specifications

  1. The first argument is a path to a file.
  2. The file contains multiple lines.
  3. Each line is a test case represented by a comma separated list of numbers and the number k, separated by a semicolon.
  4. Print the comma separated list of numbers after reversing.
  5. If the number of elements is not a multiple of k, then the remaining elements should be unaltered.

Sample Input

1,2,3,4,5;2
1,2,3,4,5;3

Sample Output

2,1,4,3,5
3,2,1,4,5

Source

My Solution

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
 public static void main(String[] args) {
 if (args.length == 0) {
 System.out.println("No file path provided.");
 System.exit(1);
 }
 if (args.length >= 2) {
 System.out.println("Excessive arguments only the first will be considered.");
 }
 
 try (Scanner file = new Scanner(new File(args[0]))) {
 while (file.hasNextLine()) {
 System.out.println(reversed(file.nextLine()));
 }
 } catch (FileNotFoundException fnfe) {
 System.err.println("Could not find file.");
 }
 }
 private static String reversed(String line) {
 String[] helper = line.split(";");
 int k = Integer.parseInt(helper[1]);
 if (k == 0) {
 return helper[0];
 }
 return reversedByK(helper[0].split(","), k);
 }
 private static String reversedByK(String[] nums, int k) {
 StringBuilder result = new StringBuilder();
 for (int i = k - 1; i < nums.length; i += k) {
 for (int j = i; i - j <= k - 1; j--) {
 result.append(',').append(nums[j]);
 }
 }
 for (int i = nums.length - nums.length % k; i < nums.length; i++) {
 result.append(',').append(nums[i]);
 }
 return result.substring(1);
 }
}
lang-java

AltStyle によって変換されたページ (->オリジナル) /