I tried two methods to limit the time to 10 seconds, but after a lot of googling I can't find anyway to limit the memory use.
I tested in the main, either way works for the time control, but the verification still times out.
Any suggestions please? Thanks in advance.
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.*;
/*
Number algorithms
*/
public class Solution {
public static long[] getNumbers(long N) throws InterruptedException {
long[] result = null;
Find find = new Find(N);
Thread t = new Thread(find);
t.start();
Thread.sleep(10000);
t.interrupt();
// ExecutorService executor = Executors.newSingleThreadExecutor();
// ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();
// Future f = executor.submit(find);
// try {
// f.get(10, TimeUnit.SECONDS);
// } catch (ExecutionException e) {
// e.printStackTrace();
// //System.out.println("over1");
// executor.shutdownNow();
// } catch (TimeoutException e) {
// // System.out.println("over2");
// executor.shutdownNow();
// }
result = find.list.stream().mapToLong(l -> l).toArray();
return result;
}
public static class Find implements Runnable{
long n;
ArrayList<Long> list = new ArrayList<>();
public Find(long N) {
n=N;
}
@Override
public void run() {
for (long s=0; s<n; s++) {
if(Thread.currentThread().isInterrupted()){
//System.out.println("over");
return;
}else {
String ss = String.valueOf(s);
int m = ss.length();
char[] numbers = ss.toCharArray();
long sum =0;
for (char c: numbers) {
//System.out.println(c);
sum += Math.pow((c-48), m);
}
if (sum==s) {
list.add(s);
}
}
}
}
}
public static void main(String[] args) throws Exception {
// long[] rrr= getNumbers(50000000);
// System.out.println(Arrays.toString(rrr));
}
}