Count triplets - First Approch

爷,独闯天下 提交于 2021-02-09 20:42:24

问题


I'm doing this exercise on HackerRank:

You are given an array and you need to find number of triplets of indices (i, j, k) such that the elements at those indices are in geometric progression for a given common ratio r and i < j < k.

Full exercise: https://www.hackerrank.com/challenges/count-triplets-1/problem I have problems with compiler. This is code:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {

    // Complete the countTriplets function below.
    static long countTriplets(List<Long> arr, long r) {
        int counter = 0;

        for (int i = 0; i < arr.length() - 2; i++) {
            for (int j = i + 1; j < arr.length() - 1; j++) {
                if (arr[j] - arr[i] == r) {
                    for (int k = j + 1; k < arr.length(); k++) {
                        if (arr[k] - arr[j] == r) {
                            System.out.println("(" + arr[i] + "," + arr[j] + "," + arr[k] + ")");
                            counter++;
                            break;
                        }

                    }
                }
            }

        }
        ;
        return counter;

    }

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nr = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int n = Integer.parseInt(nr[0]);

        long r = Long.parseLong(nr[1]);

        List<Long> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")).map(Long::parseLong)
                .collect(toList());

        long ans = countTriplets(arr, r);

        bufferedWriter.write(String.valueOf(ans));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

I have this errors:

Solution.java:19: error: cannot find symbol
for (int i = 0; i < arr.length() -2; i++){
                       ^
  symbol:   method length()
  location: variable arr of type List<Long>
Solution.java:20: error: cannot find symbol
    for(int j = i + 1; j < arr.length() -1; j++){
                              ^
  symbol:   method length()
  location: variable arr of type List<Long>
Solution.java:21: error: array required, but List<Long> found
          if(arr[j] - arr[i] == r){
                ^
Solution.java:21: error: array required, but List<Long> found
          if(arr[j] - arr[i] == r){
                         ^
Solution.java:22: error: cannot find symbol
            for(int k = j + 1; k < arr.length(); k++){
                                      ^
  symbol:   method length()
  location: variable arr of type List<Long>
Solution.java:23: error: array required, but List<Long> found
                if(arr[k] - arr[j] == r){
                      ^
Solution.java:23: error: array required, but List<Long> found
                if(arr[k] - arr[j] == r){
                               ^
Solution.java:24: error: array required, but List<Long> found
System.out.println("(" +arr[i] + "," +arr[j] + "," +arr[k] +")");
                           ^
Solution.java:24: error: array required, but List<Long> found
System.out.println("(" +arr[i] + "," +arr[j] + "," +arr[k] +")");
                                         ^
Solution.java:24: error: array required, but List<Long> found
System.out.println("(" +arr[i] + "," +arr[j] + "," +arr[k] +")");
                                                       ^
10 errors

(I'm starting out with programming, so I don't know if the code is correct)

=============================================================================

UPDATE: I don't have errors, but return 0 for each test cases.

public class Solution {

    // Complete the countTriplets function below.
    static long countTriplets(List<Long> arr, long r) {

        // Long[] a = arr.toArray();
        int counter = 0;

        for (int i = 0; i < arr.size() - 2; i++) {
            for (int j = i + 1; j < arr.size() - 1; j++) {
                if (arr.get(j) - arr.get(i) == r) {
                    for (int k = j + 1; k < arr.size(); k++) {
                        if (arr.get(k) - arr.get(j) == r) {
                            System.out.println("(" + arr.get(i) + "," + arr.get(j) + "," + arr.get(k) + ")");
                            counter++;
                            break;
                        }

                    }
                }
            }
        }
        return counter;
    }
}

回答1:


The input type for variable arr is a List and not an array of integers. List is an interface of Collection.

int[] arr = new int[]; // is the way to declare and array any element can be accessed by using arr[index]

A list can contain duplicates and elements are ordered. Example implementations are LinkedList (linked list based) and ArrayList (dynamic array based).

arr.size() is the function to get size of the collection. Also, in order to access any element in a list arr.get(index) function is used.




回答2:


Your problem is that you are mixing up two similar, but in the end: very different concepts.

static long countTriplets(List<Long> arr, long r) {

It seems you want to think of arr as of array. Because you later use the array access syntax arr[someIndex].

But well, you didn't declare it as array. You have a List there.

Then you have to use things like:

someList.getSize()

to acquire the length of the list, or

someList.get(someIndex)

to acquire a specific element in that list.

But the real answer is: when you don't understand such fundamental basic stuff, then fetching some code from somewhere, to turn it to hackerrank isn't what you should be doing right now.

Meaning: in order to successfully write your own code, to solve such exercises, you need to understand "enough" of the language already.

Thus: step back, and get a good book about Java. And work through that book.




回答3:


You need to correct the following couple of errors:

A. Use arr.length instead of arr.length()

B. Convert arr into an array before you use it in for loops. First, rename the List<Long> arr parameter in countTriplets(List<Long> arr, long r) e.g. as List<Long> list and then use the following code to convert it into a Long array:

Object []objectArray=list.toArray();
Long arr[] = Arrays.stream(objectArray).map(Object::toString)
                                       .map(Long::valueOf)
                                       .toArray(Long[]::new);


来源:https://stackoverflow.com/questions/58932807/count-triplets-first-approch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!