Threadpool with callable - java

I got struked with the ThreadPool method with callable. I want to find Large number in array as well Frequency of it occurence, so i did everything but it showing error. Anyone can help me. Thank you.
import java.util.concurrent.Callable;
public class CallableMethod im``plements Callable<Integer>{
//#SuppressWarnings("unused")
private int[] num;
public CallableMethod(int [] num){
this.num = num;
}
public Integer call() throws Exception{
int n = num[0];
int frequency = 0;
for(int i=1; i< num.length; i++)
{
if(n < num[i]){
n = num[i];
}
}
for(int i = 1; i< num.length; i++){
if (n == num[i]){
frequency++;
}
}
//System.out.println("Largest Number is : " + num);
//System.out.println("frequency of occurence : " + frequency);
return frequency;
}
}
Above one is my callabe() code and
import java.util.concurrent.*;
import java.util.*;
class ThreadPoolMethod {
// static ExecutorService pool = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
int number[] = { 32, 43, 145, 53, 25, 98, 54, 32, 65, 63, 145, 98, 43, 23, 25, 98, 100, 102, 105, 123, 145,
122, 123, 11, 12, 1, 0, 123, 145, 145 };
ArrayList<Future<Integer>> future = new ArrayList<Future<Integer>>();
for (int j = 0; j < number.length; j++) {
Future<Integer> f = pool.submit(new CallableMethod(number));
future.add(f);
}
// create array to store results
int result[] = new int[number.length];
for (int j = 0; j < result.length; j++) {
try {
Future<Integer> f = future.get(j);
result[j] = f.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
};
}
System.out.println("The Large Number in array is: " + n);
System.out.println("The : " + frequency);
pool.shutdown();
for(int x : result)
System.out.print(x);
}
}
This one is my ThreadPool. Please I'm struked. I cant call callable work into ThreadPool method.Please help me

Try to use this example on java 8 with Streams, CompletableFuture, ForkJoinPool
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
public class DemoController {
public static void main(String[] args) {
ForkJoinPool forkJoinPool = new ForkJoinPool(2);
int number[] = {32, 43, 145, 53, 25, 98, 54, 32, 65, 63, 145, 98, 43, 23, 25, 98, 100, 102, 105, 123, 145,
122, 123, 11, 12, 1, 0, 123, 145, 145};
List<CompletableFuture<Integer>> future = new ArrayList<>();
for (int j = 0; j < number.length; j++) {
CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> func(number), forkJoinPool);
future.add(f);
}
List<Integer> result = future.stream().map(f -> {
try {
return f.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
forkJoinPool.shutdown();
result.forEach(System.out::println);
}
private static Integer func(int num[]) {
int n = num[0];
int frequency = 0;
for (int i = 1; i < num.length; i++) {
if (n < num[i]) {
n = num[i];
}
}
for (int i = 1; i < num.length; i++) {
if (n == num[i]) {
frequency++;
}
}
System.out.println("Largest Number is : " + n);
System.out.println("frequency of occurence : " + frequency);
return frequency;
}
}

Related

returning a sub-array of size n, assume the size of n is between 1 and bestTime.length, and return with the lowest sub arrays

int[] bestTime = {50, 73, 72, 75, 71, 56, 61, 60, 62, 68, 70, 50, 70};
assume if n = 6, expected return = {50, 50, 56, 60, 61, 62}
this is what i have so far, i know there are lots of mistakes. any suggestions is much appreciated.
public static int[] bestRun(int n) {
int[] best = bestTime[0];
for(int i = 0; i <= bestTime.length; i++ ) {
if(bestTime[i] <= best) {
best = bestTime[i];
best++;
} return best;
}
if(best.length == n) {
return best;
}
return null;
}
Build an IntStream of your bestTime array, sort them, limit using n, convert to array and return:
public static int[] bestRun(int n) {
return IntStream.of(bestTime).sorted().limit(n).toArray();
}
You can do the task also using classic for loops. But then you need to implement the sorting yourself. Something like below should give you a how this can be accomplished:
static int[] bestTime = {50, 73, 72, 75, 71, 56, 61, 60, 62, 68, 70, 50, 70};
public static void main(String args[]) throws IOException{
int[] best = bestRun(6);
System.out.println(Arrays.toString(best));
}
public static int[] bestRun(int n) {
//copy your bestTime array
int[] copy = new int[bestTime.length];
for(int i = 0; i < copy.length; i++){
copy[i] = bestTime[i];
}
//sort copy
for (int i = 0; i < copy.length; i++) {
for (int j = i+1; j < copy.length; j++) {
int temp = 0;
if(copy[i] > copy[j]) {
temp = copy[i];
copy[i] = copy[j];
copy[j] = temp;
}
}
}
//fill your result array
int[] result = new int[n];
for(int i = 0; i < n; i++){
result[i] = copy[i];
}
return result;
}

How to sort only odd integers from an array of both odd and even integers and only display the sorted odd integer?

here is the integer array given to me 111,77, 88, 44, 32, 11, 13, 25, 44 I need to sort & display only the odd elements of the array .
I had tried solving it using loops and if condition
i had expected the output as 11 13 25 77 111
import java.lang.reflect.Array;
public class oddsortSolution {
public static void main(String args[]) {
int n[] = { 111, 77, 88, 44, 32, 11, 13, 25, 44 };
int i = 0;
int temp = 0;
while (i < n.length) {
if (n[i] % 2 != 0) {
for (int j = i + 1; j < n.length; j++) {
if (n[j] > n[i]) {
n[j] = temp;
n[j] = n[i];
n[i] = temp;
}
}
}
}
System.out.println(n[1]);
}
}
You basically need to keep track of your odd array size, increment it every time you find an odd value, determine if the value should be swapped somewhere in the existing array (ranging from 0 to oddArraySize) and insert it in the correct position. Try the following code,
public class oddsortSolution {
public static void main(String args[]) {
int n[] = { 111, 77, 88, 44, 32, 11, 13, 25, 44 };
int oddArraySize = 0;
for (int i = 0;i < n.length; i++) {
if (n[i] % 2 != 0) {
oddArraySize++;
for (int j = 0; j < oddArraySize; j++) {
if (j == oddArraySize - 1) {
n[j] = n[i];
} else if (n[j] > n[i]) {
int temp = n[j];
n[j] = n[i];
n[i] = temp;
}
}
}
}
int[] oddArray = Arrays.copyOfRange(n, 0, oddArraySize);
System.out.println( Arrays.toString( oddArray ));
}
}

How to convert 5 1D arrays to a 2D array

So i have to create a bingo board which i have done so, don't mind the long code it's repetitive for the first column method. So i wanna convert these 5 1D arrays to 1 2D array so i can check for a bingo. Could someone explain to me in detail how i would convert these 5 arrays to 1 2D array, or if it's possible to check 5 1D arrays.
package bingo;
import static java.rmi.Naming.list;
import java.util.ArrayList;
import java.util.Collections;
import static java.util.Collections.list;
import java.util.List;
public class Bingo {
public static void main(String[] args) {
int[][] card1 = new int[5][5];
int[] column1 = new int[5];
int[] column2 = new int[5];
int[] column3 = new int[5];
int[] column4 = new int[5];
int[] column5 = new int[5];
column1(column1);
System.out.println("");
column2(column2);
System.out.println("");
column3(column3);
System.out.println("");
column4(column4);
System.out.println("");
column5(column5);
System.out.println("");
cardofzeros(card1);
for (int i = 0; i < card1.length; i++) {
for (int j = 0; i < card1.length; i++) {
}
}
}
public static void column1(int[] column1) {
int[] colm = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
List l = new ArrayList();
for (int i : colm) {
l.add(i);
}
Collections.shuffle(l);
for (int i = 0; i < 5; i++) {
System.out.print("|" + l.get(i));
}
}
public static void column2(int[] column2) {
int[] colm2 = {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
List l = new ArrayList();
for (int i : colm2) {
l.add(i);
}
Collections.shuffle(l);
for (int i = 0; i < 5; i++) {
System.out.print("|" + l.get(i));
}
}
public static void column3(int[] column3) {
int[] colm3 = {31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45};
List l = new ArrayList();
for (int i : colm3) {
l.add(i);
}
Collections.shuffle(l);
for (int i = 0; i < 5; i++) {
System.out.print("|" + l.get(i));
}
}
public static void column4(int[] column4) {
int[] colm4 = {46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60};
List l = new ArrayList();
for (int i : colm4) {
l.add(i);
}
Collections.shuffle(l);
for (int i = 0; i < 5; i++) {
System.out.print("|" + l.get(i));
}
}
public static void column5(int[] column5) {
int[] colm2 = {61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75};
List l = new ArrayList();
for (int i : colm2) {
l.add(i);
}
Collections.shuffle(l);
for (int i = 0; i < 5; i++) {
System.out.print("|" + l.get(i));
}
}
public static void cardofzeros(int[][] card1) {
for (int i = 0; i < 5; i++) {
for (int j = 0; i < 5; i++) {
card1[i][j]=0;
System.out.print("|"+card1[i][j]);
}
}
}
}
int[] first = null;
int[] second = null;
int[] third = null;
int[] fourth = null;
int[] fifth = null;
int[][] arr2d = new int[][]{first , second , third , fourth , fifth};

Display two 1D and one 2D arrays in table form

I am Java learner and testing Java code and do not have much grip in Java at the moment.
At the moment what I want to achieve is that I have two 1D arrays of String and One 2D array of Integers. I want the results to be displayed in a table form but I am unable to do so. My code is below.
import java.util.*;
public class StudentResults {
static String studentName;
static String courseName;
static int courseMarks;
static String[] student = { "Jack Smith", "Jim Lucas", "Beck Barber",
"Ann Walker", "Lucy Boxer" };
static String[] course = { "Maths", "Business", "Java", "Design", "Project" };
public static void studentMarks() {
int[][] marks = { { 89, 70, 56, 87, 65 }, { 70, 65, 70, 83, 78 },
{ 60, 90, 63, 56, 79 }, { 74, 78, 45, 73, 85 },
{ 80, 90, 60, 70, 80 } };
for (int i = 0; i < student.length; i++) {
studentName = student[i];
System.out.printf("\t\t" + studentName + "\t");
}
System.out.println("");
for (int j = 0; j < course.length; j++) {
courseName = course[j];
System.out.println(courseName + "\t");
}
for (int m = 0; m < marks.length; m++) {
for (int n = 0; n < marks.length; n++) {
courseMarks = marks[m][n];
System.out.print("\t\t" + courseMarks + "\t\t");
}
System.out.println("");
}
}
public static void main(String args[]) {
studentMarks();
}
}
The output I am getting for the marks is in table but not inline with the course name. Just want to know if there is a way I can achieve this with the way I am working.
Cheers,
I assume this is some kind of homework (or self study) so l will give a hint rather than the full solution:
You want to print each subject, followed by each mark for that particurlar subject.
Currently, you are printing a list of all subjects, then you are printing the marks for each subject afterwards.
So this part of your code:
for (int j = 0; j < course.length; j++) {
courseName = course[j];
System.out.println(courseName + "\t");
}
for (int m = 0; m < marks.length; m++) {
for (int n = 0; n < marks.length; n++) {
courseMarks = marks[m][n];
System.out.print("\t\t" + courseMarks + "\t\t");
}
System.out.println("");
}
Should be a nested loop rather than two separate loops. ie, the second loop should be inside the first loop.
So you print one subject, then all the marks for that subject, then the next subject, then all the marks for that second subject and so on
There is still a bit of fiddling around before you will get the exact layout you want.But remember that System.out.println() will print the argument followed by a new line.
Remove the second for loop for printing the course and add the logic to print course in the third loop.
Code should look like this.
import java.util.*;
public class StudentResults {
static String studentName;
static String courseName;
static int courseMarks;
static String[] student = { "Jack Smith", "Jim Lucas", "Beck Barber",
"Ann Walker", "Lucy Boxer" };
static String[] course = { "Maths", "Business", "Java", "Design", "Project" };
public static void studentMarks() {
int[][] marks = { { 89, 70, 56, 87, 65 }, { 70, 65, 70, 83, 78 },
{ 60, 90, 63, 56, 79 }, { 74, 78, 45, 73, 85 },
{ 80, 90, 60, 70, 80 } };
for (int i = 0; i < student.length; i++) {
studentName = student[i];
System.out.printf("\t\t" + studentName + "\t");
}
System.out.println("");
/*for (int j = 0; j < course.length; j++) {
courseName = course[j];
System.out.println(courseName + "\t");
}*/
for (int m = 0; m < marks.length; m++) {
courseName = course[m];
System.out.print(courseName + "\t\t");
for (int n = 0; n < marks.length; n++) {
courseMarks = marks[m][n];
System.out.print("\t\t" + courseMarks + "\t\t");
}
System.out.println("");
}
}
public static void main(String args[]) {
studentMarks();
}
}

Adding the diagonal values in a 2d array

I have the following 2d array
int [][] array = {{ 0, 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, 52, 53, 54, 55, 56, 57, 58, 59},
{60, 61, 62, 63, 64, 65, 66, 67, 68, 69},
{70, 71, 72, 73, 74, 75, 76, 77, 78, 79},
{80, 81, 82, 83, 84, 85, 86, 87, 88, 89},
{90, 91, 92, 93, 94, 95, 96, 97, 98, 99}};
I have this code to find the sum of all the values in the array. How can I modify it to add only the diagonal values starting at 0 (0+11+22+33 etc.)?
public static int arraySum(int[][] array)
{
int total = 0;
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[row].length; col++)
total += array[row][col];
}
return total;
}
Since the diagonals are at perfect square you only need one loop to add the diagonals.
Adding diagonal from orgin:
public static int arraySum(int[][] array){
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row];
}
return total;
}
Add both diagonals:
Adding diagonal from orgin: (note it adds the center twice..you can subtract one if needed)
public static int arraySum(int[][] array){
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row] + array[row][array.length - row-1];
}
return total;
}
public static int arraySum(int[][] array)
{
int total = 0;
for (int index = 0; index < array.length; index++)
{
total += array[index][index];
}
return total;
}
This of course assumes m x m for the dimensions.
Here is my solution -
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
for(int a_i=0; a_i < n; a_i++){
for(int a_j=0; a_j < n; a_j++){
a[a_i][a_j] = in.nextInt();
}
}
int l_sum = 0;
for(int i = 0; i<n ; i++){
l_sum+=a[i][i];
}
int r_sum = 0;
for(int j = 0; j<n ; j++){
r_sum+=a[j][n-1-j];
}
int sum = l_sum + r_sum;
System.out.println(sum);
}
}
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int leftStartDiagnol = 0;
int rightStartDiagnol = n;
int leftTotal = 0;
int rightTotal = 0;
int a[][] = new int[n][n];
for (int a_i = 0; a_i < n; a_i++) {
for (int a_j = 0; a_j < n; a_j++) {
a[a_i][a_j] = in.nextInt();
}
}
for (int a_i = 0; a_i < n; a_i++) {
boolean leftNotFound = true;
boolean rightNotFound = true;
rightStartDiagnol = --rightStartDiagnol;
for (int a_j = 0; a_j < n; a_j++) {
if (leftStartDiagnol == a_j && leftNotFound) {
leftTotal = leftTotal + a[a_i][a_j];
leftNotFound = false;
}
if (rightStartDiagnol == a_j && rightNotFound) {
rightTotal = rightTotal + a[a_i][a_j];
rightNotFound = false;
}
}
leftStartDiagnol = ++leftStartDiagnol;
}
int data = leftTotal - rightTotal;
System.out.println(Math.abs(data));
}
}
Here is my solution. Check out it.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
int total1=0;
int total2=0;
for(int a_i=0; a_i < n; a_i++){
for(int a_j=0; a_j < n; a_j++){
a[a_i][a_j] = in.nextInt();
}
total1+= a[a_i][a_i];
total2+=a[a_i][n-1-a_i];
}
System.out.println(Math.abs(total1-total2));
}
}
import java.io.*;
import java.util.*;
public class DigArraySum {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=Integer.parseInt(s.nextLine()); //array size
int[][] a=new int[n][n]; // new array
for (int i=0;i<n;i++) {
String str=s.nextLine();
String[] tempArray=str.split(" ");
for (int j=0;j<n;j++) {
a[i][j]=Integer.parseInt(tempArray[j]);
}
}
int x=0;//primary diagonal sum
int y=0;//secondary diagonal sum
int sum=0;//total sum
for (int i=0;i<n;i++) {
x += a[i][i];
}
for (int p=0;p<n;p++) {
int k=a.length-p-1;
y+=a[p][a.length-p-1];
k+=-1;
}
sum=x-y;
System.out.println(Math.abs(sum));
}
}
Explanation:
for example 3*3 matrix:
3// Array size
11 2 4
4 5 6
10 8 -12
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Total Sum: |4 + 19| = 23
Solution in PHP. The logic is exactly the same what is already posted here. It's only in PHP that's different.
<?php
$handle = fopen ("php://stdin", "r");
function diagonalDifference($a) {
$sumA = [];
$sumB = [];
$n = count($a);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($i === $j) {
$sumA[] = $a[$i][$j];
}
if ($i + $j == count($a) -1 ) {
$sumB[] = $a[$i][$j];
}
}
}
$sum1 = array_sum($sumA);
$sum2 = array_sum($sumB);
return abs($sum1 - $sum2);
}
fscanf($handle, "%i",$n);
$a = array();
for($a_i = 0; $a_i < $n; $a_i++) {
$a_temp = fgets($handle);
$a[] = explode(" ",$a_temp);
$a[$a_i] = array_map('intval', $a[$a_i]);
}
$result = diagonalDifference($a);
echo $result . "\n";
?>
The solution is:
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row] + array[row][array.length - row - 1];
}
System.out.println("FINAL ANSWER: " + total);
Here is the code which I did to find the sum of primary diagonal numbers and secondary diagonal numbers
static int diagSum(int[][] arr) {
int pd=0;
int sd=0;
int sum=0;
for(int i=0;i<=arr.length-1;i++){
pd=pd+arr[i][i];
}
for (int k=0,l=arr.length-1; k<arr.length&&l>=0 ; k++,l--) {
sd=sd+arr[k][l];
}
sum=pd+sd;
return sum;
}
difference between the sums of its diagonals in kotlin :
val total = (0 until array.size).sumBy { array[it][it] - array[it][array.size - it - 1] }
if you want absolute difference:
return Math.abs(total)
public class matrix {
public static void main(String[] args) {
int sum=0;
int a[][]= new int[][]{{2,3,4},{4,5,6},{5,5,5}};
for(int i=0;i<=2;i++)
{
sum=sum+a[i][i];
}
System.out.println(sum);
}
}
If you want to add both diagonal in a 2d array then here is my program.
static int diagonalDifference(int[][] arr) {
int r = arr.length;
int sum1 = 0;
int sum2 = 0;
int j=0;
for(int i=0;i<r;i++){
sum1 = sum1 + arr[i][j];
j++;
}
j--;
for(int i=0;i<r;i++) {
sum2 = sum2 + arr[i][j];
j--;
}
int sum=sum1+sum2;
return sum;
}
If you want to add both diagonal in a 2d array then here is a solution:
int j = row_col_size-1;
for (int i = 0; i < intArray.length; i++) {
sum_left += intArray[i][i];
sum_right += intArray[i][j];
j--;
}
Although this post is very old. Providing my solution. This might be useful for someone
func diagonalDifference(arr [][]int32) int32 {
return int32(math.Abs(float64(arraySumPrimary(arr)) - float64(arraySumSecondary(arr))) )
}
func arraySumPrimary(arr [][]int32) int32{
var total int32 =0
for row :=0; row < len(arr) ; row ++{
total = total + arr[row][row]
}
return total
}
func arraySumSecondary(arr [][]int32) int32{
var total int32 =0
x := len(arr)-1
y := 0
for x >=0 && y < len(arr){
total = total + arr[x][y]
x--
y++
}
return total
}

Categories

Resources