Prims algorithm to Dijkstra algorithm - java

I am trying to make my existing implementation of Prim's algorithm to keep track distances from source . Since prim's and Dijkstra's algorithm are almost same. I can't figure out where am I missing something.
I know what the problem is but cannot figure it out.
Here is my code, how do I modify it to print the shortest distance from source to all other vertex. Shortest distance is stored in array named : dist[]
Code:
package Graphs;
import java.util.ArrayList;
public class Prims {
static int no_of_vertices = 0;
public static void main(String[] args) {
int[][] graph = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
no_of_vertices = graph.length;
int [][] result = new int [no_of_vertices][no_of_vertices];
boolean[] visited = new boolean[no_of_vertices];
int dist[] = new int[no_of_vertices];
for (int i = 0; i < no_of_vertices; i++)
for (int j = 0; j < no_of_vertices; j++) {
result[i][j]= 0;
if (graph[i][j] == 0) {
graph[i][j] = Integer.MAX_VALUE;
}
}
for (int i = 0; i < no_of_vertices; i++) {
visited[i] = false;
dist[i] = 0;
}
ArrayList<String> arr = new ArrayList<String>();
int min;
visited[0] = true;
int counter = 0;
while (counter < no_of_vertices - 1) {
min = 999;
for (int i = 0; i < no_of_vertices; i++) {
if (visited[i] == true) {
for (int j = 0; j < no_of_vertices; j++) {
if (!visited[j] && min > graph[i][j]) {
min = graph[i][j];
dist[i] += min; // <------ Problem here
visited[j] = true;
arr.add("Src :" + i + " Destination : " + j
+ " Weight : " + min);
}
}
}
}
counter++;
}
for (int i = 0; i < no_of_vertices; i++) {
System.out.println("Source : 0" + " Destination : " + i
+ " distance : " + dist[i]);
}
for (String str : arr) {
System.out.println(str);
}
}
}
There is a mistake in calculation of distance array as it forgets to add the distance of any intermediate nodes from source to destination.

for (int j = 0; j < no_of_vertices; j++) {
if (!visited[j] && min > graph[i][j]) {
min = graph[i][j];
dist[i] += min; // <------ Problem here
Of course intermediate edges don't get added, because you only add the current edge. You probably want something like:
if (dist[i] + graph[i][j] < dist[j])
dist[j] = dist[i] + graph[i][j];
And get rid of the min variable.
Although your algorithm does not look correct to me. You're supposed to pick the node with minimum d[] at each step, and update that node's neighbors as I wrote above, then mark it as picked and never pick it again.

Related

How to remove duplicated list from a list of list?

Is there some elegant ways to remove duplicated list (list with same values) from a list of list?
I tried with Set<List<Integer>> but it's not working, it still shows the duplicated lists. It seems that Set only checks the object reference.
the example code:
int[] nums = {-1, 0, 1, 2, -1, -4};
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
set.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
then the set will contain 3 elements but two of them have the same values.
A repair:
record Triple(int x, int y, int z) {};
int[] nums = {-1, 0, 1, 2, -1, -4};
Set<Triple> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
set.add(new Triple(nums[i], nums[j], nums[k]));
}
}
}
}
However the algorithm is suboptimal O(n³).
record Triple(int x, int y, int z) {};
int[] nums = {-1, 0, 1, 2, -1, -4};
Arrays.sort(nums);
Set<Triple> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
int numI = num[i];
for (int j = i + 1; j < nums.length; j++) {
int numJ = num[j];
int numK = -(numI + numK);
int k = Arrays.binarySearch(nums, j + 1, nums.length, numK);
if (k >= 0) { // Found
set.add(new Triple(numI, numJ, numK));
}
}
}
binarySearch delivers a non-negative index when it finds the search key. When negative, it delivers the 1s complement of the "insert" position.
This has complexity O(n².log n). You determine the found resp. insert position in the for-i loop and in the for-j loop decrement k a couple of times to find the sum. That would not be difficult but less readable.
Mind the resulting numbers are ordered.

Reconstructing the path that gives the maximum path sum in a matrix

I'm trying to find a maximum path sum in the matrix. The starting position must be in a[0][0] (top-left) and the ending position must be in a[n][m] (bottom-right). The move is only allowed to the right, down, or diagonal.
Here is my solution:
public class Main {
public static int maxa(int[][] a) {
int m = a.length, n = a[0].length;
int[][] dp = new int[m][n];
dp[0][0] = a[0][0];
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0] + a[i][0];
}
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j - 1] + a[0][j];
}
System.out.println("Route Path: ");
System.out.print(a[0][0] + " ");
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = findMax(dp[i - 1][j], dp[i][j - 1], dp[i-1][j-1]) + a[i][j];
if (a[i - 1][j] > a[i][j - 1]) {
System.out.print(a[i - 1][j] + " ");
} else {
System.out.print(a[i][j - 1] + " ");
}
}
}
System.out.print(a[m - 1][n - 1] + " ");
System.out.println();
System.out.println("Result: ");
return dp[m - 1][n - 1];
}
public static int findMax(int num1, int num2, int num3) {
if (num1 >= num2 && num1 >= num3)
return num1;
else if (num2 >= num1 && num2 >= num3)
return num2;
else
return num3;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int MAX = 30;
int MIN = -30;
Random random = new Random();
System.out.print("Enter values of Rows: ");
int n = input.nextInt();
System.out.print("Enter values of Columns: ");
int m = input.nextInt();
int[][] myMatrix = new int[n][m];
for (int row = 0; row < n; row++) {
for (int col = 0; col < m; col++) {
// myMatrix[row][col] = random.nextInt(MAX - MIN) + MIN;
myMatrix[row][col] = input.nextInt();
}
}
System.out.println();
System.out.println("Your Random Matrix: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(myMatrix[i][j] + "\t");
}
System.out.println();
}
System.out.println();
System.out.println(maxa(myMatrix));
}
}
The result of the sum is correct but my code gives the wrong route path.
For example, if I have a 3x3 matrix = [{1,2,3},{4,-5,6},{7-8,9}], then the result sum I get is 22 which is correct, but the route path I get is 1 4 3 -5 8 9 which is wrong. I expected my route path output to be 1 4 8 9.
What can I do to fix the problem and produce the correct path?
I'm not sure I follow your expected output, but the inline prints are generally not a great approach to the problem. Generally, you want to compute it without a side effect and return it so the caller can use the result programmatically, optionally to print.
In any case, your printing condition if (a[i - 1][j] > a[i][j - 1]) isn't enough to differentiate which of 3 possible moves was chosen on the best path. We need to find the largest of 3 subproblems in the DP table, not the input matrix -- looking at a is meaningless because it's only a local maxima at best.
In the case of a tie, it doesn't matter which move we pick from the DP table, all tied subproblems have equally maximal path scores.
While it's possible to figure out which number was taken along the way up by making that 3-way comparison, the typical(?) approach I'm familiar with for DP is to backtrack from dp[m-1][n-1] to dp[0][0] and reconstruct the path based on the DP table. It's free lunch from a time complexity standpoint and lets you separate the logic into a distinct function.
The logic for rebuilding the path is:
Start at i = m - 1, j = n - 1 (the bottom-right corner).
Repeat until i == 0 and j == 0 (the top-left corner):
Add a[i][j] to the path.
If i > 0 and j > 0, find the best of dp[i-1][j], dp[i-1][j-1], dp[i][j-1]. If the best was [i-1][j-1], decrement both i and j by 1 -- we took a diagonal move; otherwise decrement either i or j depending on which move was better.
Otherwise, i == 0 or j == 0 and the path is on a top or left edge and we'll just decrement i or j until we get to the goal.
Add a[0][0] to the path, reverse it and return it.
Here's a proof of concept:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static int maxPathSum(int[][] a) {
final var table = makeDPTable(a);
if (table.length > 0 && table[0].length > 0) {
return table[table.length-1][table[0].length-1];
}
return 0;
}
public static ArrayList<Integer> maxPath(int[][] a) {
return reconstructPath(makeDPTable(a), a);
}
private static ArrayList<Integer> reconstructPath(int dp[][], int a[][]) {
final int m = a.length;
if (m == 0) {
return new ArrayList<Integer>();
}
final int n = a[0].length;
final var path = new ArrayList<Integer>();
for (int i = m - 1, j = n - 1; i > 0 || j > 0;) {
path.add(a[i][j]);
if (i > 0 && j > 0) {
final int bestIdx = indexOfMax(
dp[i-1][j-1],
dp[i][j-1],
dp[i-1][j]
);
switch (bestIdx) {
case 0: i--;
case 1: j--; break;
case 2: i--; break;
}
}
else if (i > 0) {
i--;
}
else {
j--;
}
}
path.add(a[0][0]);
Collections.reverse(path);
return path;
}
private static int[][] makeDPTable(int[][] a) {
final int m = a.length;
if (m == 0) {
return new int[0][0];
}
final int n = a[0].length;
final var dp = new int[m][n];
dp[0][0] = a[0][0];
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i-1][0] + a[i][0];
}
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j-1] + a[0][j];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = a[i][j] + max(
dp[i-1][j],
dp[i][j-1],
dp[i-1][j-1]
);
}
}
return dp;
}
private static int max(int ...nums) {
if (nums.length == 0) {
throw new IllegalArgumentException("nums cannot be empty");
}
int largest = nums[0];
for (int num : nums) {
largest = Math.max(num, largest);
}
return largest;
}
private static int indexOfMax(int ...nums) {
if (nums.length == 0) {
return -1;
}
int largest = nums[0];
int idx = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > largest) {
largest = nums[i];
idx = i;
}
}
return idx;
}
private static void print(int[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
System.out.print(StringUtils.padLeft(m[i][j], 3));
}
System.out.println();
}
}
public static void main(String[] args) {
var tests = new TestCase[] {
new TestCase(
new int[][] {
{1, 2, 3},
{4,-5, 6},
{7,-8, 9},
},
new ArrayList<Integer>(Arrays.asList(1, 2, 3, 6, 9)),
21
),
new TestCase(
new int[][] {
{1, 2, 3},
{4,-5, 6},
{7, 8, 9},
},
new ArrayList<Integer>(Arrays.asList(1, 4, 7, 8, 9)),
29
),
new TestCase(
new int[][] {
{1, 2, 3, 20},
{4,-5, 6, -5},
{7, 8, 9, 10},
},
new ArrayList<Integer>(Arrays.asList(1, 4, 7, 8, 9, 10)),
39
),
new TestCase(
new int[][] {
{1, 2, 3, -2},
{4,-5, -1, 20},
{0, 0, 9, 10},
},
new ArrayList<Integer>(Arrays.asList(1, 2, 3, 20, 10)),
36
),
new TestCase(
new int[][] {
{-1, -2, -3, -2},
{-4, -5, -1, -2},
},
new ArrayList<Integer>(Arrays.asList(-1, -2, -1, -2)),
-6
),
new TestCase(new int[][] {}, new ArrayList<Integer>(), 0),
};
for (var testCase : tests) {
if (maxPathSum(testCase.m) != testCase.expectedSum) {
print(testCase.m);
System.out.println("got sum: " + maxPathSum(testCase.m));
System.out.println("expected: " + testCase.expectedSum + "\n");
}
if (!maxPath(testCase.m).equals(testCase.expectedPath)) {
print(testCase.m);
System.out.println("got path: " + maxPath(testCase.m));
System.out.println("expected: " + testCase.expectedPath + "\n");
}
}
}
}
class TestCase {
public final int[][] m;
public final ArrayList<Integer> expectedPath;
public final int expectedSum;
public TestCase(
int[][] m,
ArrayList<Integer> expectedPath,
int expectedSum
) {
this.m = m;
this.expectedPath = expectedPath;
this.expectedSum = expectedSum;
}
}
class StringUtils {
public static <T> String padLeft(T t, int n) {
return String.format("%" + n + "s", t);
}
}

Find the most common value from a 2D integer array

I am looking for the most common value from the 2D array and how many times it occurs. I tried this solution but it's not working. I tried searching but not able to find a proper example. Please help me solve this problem.
Here is my code:
private void commonElevation(int[][] data) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (i + 1 < data.length) {
if (data[i][j] == data[i + 1][j]) {
System.out.println(data[i][j] + " = " + data[i + 1][j]);
}
}
}
}
}
You could use the Stream API:
int[][] data = {{1, 2, 3}, {2, 2, 2}, {4, 5, 6}};
Map<Integer, Long> counts = Arrays.stream(data).flatMapToInt(Arrays::stream).boxed()
.collect(groupingBy(Function.identity(), counting()));
Optional<Map.Entry<Integer, Long>> max = counts.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue));
max.ifPresent(System.out::println);
Output
2=4
Given the new constraints a brute-force approach will work:
// find the maximum
int value = 0, max = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
// search for counts
int currentCount = 0;
for (int k = 0; k < data.length; k++) {
for (int l = 0; l < data[k].length; l++) {
if(data[k][l] == data[i][j]) {
currentCount++;
}
}
}
if (currentCount > max) {
value = data[i][j];
max = currentCount;
}
}
}
System.out.println(value + "=" + max);
Output
2=4
Basically iter over all values and count the appearances of each of those values. This approach (brute-force) is very inefficient.
One possibility would be to use a hash map to keep track of the values along with the number of times each occurs:
private void commonElevation(int[][] data) {
Map<Integer, Integer> counts = new HashMap<>();
for (int i=0; i < data.length; i++) {
for (int j=0; j < data[i].length; j++) {
int count = counts.get(data[i][j]) == null ? 0 : counts.get(data[i][j]);
counts.put(data[i][j], ++count);
}
}
int frequent = Integer.MIN_VALUE;
for (Integer value : counts.values()) {
if (value > frequent) frequent = value;
}
System.out.println("most frequent value is: " + frequent);
}

Problems in ArrayList<Integer>

import java.util.*;
import java.util.Random;
class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
int dupe = 0;
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
//remove second num if two numbers akike
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n-dupe;
dupe = 0;
}
System.out.println("Duplicates: " + (20 - arr.size()));
for (int n3 = arr.size(); n3 < 20; ++n3) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
//check for duplicates again
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n - dupe;
dupe = 0;
}
}
//before sort
System.out.println(arr);
System.out.println("");
for(int a=0; a<20; a++){
for (int b = 0; b < 19; b++) {
if(arr[b] > arr[b+1]){
int temporary = arr[b];
arr[b] = arr[b+1];
arr[b+1] = temporary;
}
}
}
System.out.println("\nSorted Array:\n");
for (int a = 0; a < 20; a++) {
System.out.println("Array [" + a + "]: " + arr[a]);
}
}
}
Can anyone tell me what I did wrong for this one, I can't seem to generate the last part. Shouldn't the ArrayList arr = new ArrayList(); run same with the last part where arr[b] is work? I'm new to Java so would greatly appreciate if simple explaination/metaphor is ued provided with solution.
P.S: I'm not planning to use a library sort function like Collection, I'm required to use the sorting method at the last part.
arr[a] is the syntax to access array elements. For ArrayLists you use arr.get(a). And to assign a value to an ArrayList, you use arr.set(b,value). You can't use the assignment operator.
The problem you are having is that you are trying to remove your duplicates before sorting. First, sort your integers, duplicates and all, and then remove the duplicates.
import java.util.ArrayList;
import java.util.Random;
public class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(10);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
// SORT YOUR LIST FIRST
bubbleSort(arr);
System.out.println(arr);
// NOW YOU CAN REMOVE YOUR DUPLICATES
removeDuplicates(arr);
System.out.println(arr);
}
public static void bubbleSort(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
for(int j = 1; j < (list.size() -i); j++) {
if(list.get(j - 1) > list.get(j)) {
int temp = list.get(j-1);
list.set(j-1, list.get(j));
list.set(j, temp);
}
}
}
}
public static void removeDuplicates(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
if(i < list.size()-1) {
int prev = list.get(i);
int curr = list.get(i + 1);
if(curr == prev) {
list.remove(list.get(i + 1));
i--;
}
}
}
}
}
Output
First list of 20 generated numbers:
[9, 2, 2, 1, 3, 4, 0, 9, 5, 2, 5, 7, 4, 9, 0, 4, 0, 6, 6, 6]
[0, 0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7, 9, 9, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 9]

Wrong computatation inside the nested loops

The goal of the code is to find the numbers that add up to the targetNumber. For example, if the targetNumber = 9 then the code should get the first two occuring indexes of the numbers that add up to the targetNumber. When I run my code, the output looks like the following:
The indexes are 10 and 1
What's wrong with the logic of the code? Thanks in advance!
public class TwoSum {
public static void main(String[] args){
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
int index1 = 0;;
int index2 = 0;
for(int i = 0; i < myArray.length; i++){
for(int j = 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
index1 = i;
index2 = j;
break;
}
}
}
System.out.println("The indexes are " + index1 + " and " + index2);
}
}
When you break, you only break out of the inner loop, so instead of printing out 1 and then 10, the outer loop continues, terminating naturally, and resulting in the print out of index 10 then index 1.
An interesting result of this is that your code essentially finds the last pair of numbers that sum to targetNumber, rather than the first. If you made your for loops count down instead of up, the code should spit out the correct values, although it wouldn't be very efficient...
I believe you're expecting indexes 0 and 8 (values 1 and 8). The problem is that your break statement only breaks from the inner loop and not the outer loop. You need to use a flag to know that you also should break from the outer loop. Also consider printing a message if no match is found.
public static void main(String[] args) throws Exception {
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
int index1 = 0;
int index2 = 0;
boolean stop = false;
for (int i = 0; i < myArray.length && !stop; i++) {
for (int j = i + 1; j < myArray.length && !stop; j++) {
if (myArray[i] + myArray[j] == targetNumber) {
stop = true;
index1 = i;
index2 = j;
}
}
}
System.out.println(stop
? "The indexes are " + index1 + " and " + index2
: "No match found");
}
Or just print the results inside the inner loop and use a return instead of a break. This way you don't have to use a flag.
public static void main(String[] args) throws Exception {
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
for(int i = 0; i < myArray.length; i++){
for(int j = i + 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
System.out.println("The indexes are " + i + " and " + j);
return;
}
}
}
System.out.println("No match found");
}
Results:
The indexes are 0 and 8
To make the code a little cleaner; that is, entirely foregoing the break statement, you should introduce a boolean variable called found to your loops. This way, you can break out of both of them more intuitively if you find your first match.
boolean found = false;
for(int i = 0; i < myArray.length && !found; i++){
for(int j = 1; j < myArray.length && !found; j++){
if(myArray[i] + myArray[j] == targetNumber){
found = true;
index1 = i;
index2 = j;
}
}
}
System.out.println("The indexes are " + index1 + " and " + index2);
If you're ever curious about what other pairs of numbers add up to your target, create a Pair<T> class which can store that kind of info. You wouldn't break out of any loops as you're essentially bruteforcing the entire thing.
class Pair<T> {
final T firstValue;
final T secondValue;
Pair(T firstValue, T secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
public T getFirstValue() {
return firstValue;
}
public T getSecondValue() {
return secondValue;
}
#Override
public String toString() {
return "{" + firstValue + ", " + secondValue + "}";
}
}
// later in your code
List<Pair<Integer>> pairs = new ArrayList<>();
for(int i = 0; i < myArray.length; i++){
for(int j = 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
pairs.add(new Pair<>(i, j));
}
}
}
System.out.println("The indexes are " + pairs);
The above prints out:
The indexes are [{0, 8}, {1, 7}, {1, 10}, {5, 7}, {5, 10}, {7, 1}, {7, 5}, {10, 1}, {10, 5}]
The break statement is breaking the inner loop but not the outer one. So its getting the last result of 3 and 6 instead of the 1 and 8.
A more appropriate way may be:
bool found=false;
for(int i = 0; i < myArray.length; i++){
if(!found){
for(int j = 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
index1 = i; index2 = j;
found=true;
break;
} } }}
There are three things that are wrong with your code:
According to specification, you want to find first matching indices, while
you actually are finding last. That happens because break breaks only inner loop. The easy fix is to use label (outer:). Although the cleaner approach would be using dedicated method to do the search and return the first matched value.
You are checking pairs of indices twice and also checking pairs of the same index. The idiomatic approach that eliminates this redundancy is to start nested loop from the current value of the index of the outer loop (j = i) or (j = i + 1) if you don't want to have pairs of the same index (i, i).
You are not considering the situation when no matching index is found. In this case you will show that (0,0) is the result.
Here is your code fixed:
public static class TwoSum {
public static void main(String[] args) {
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
int index1 = -1;
int index2 = -1;
outer:
for (int i = 0; i < myArray.length; i++) {
for (int j = i + 1; j < myArray.length; j++) {
if (myArray[i] + myArray[j] == targetNumber) {
index1 = i;
index2 = j;
break outer;
}
}
}
if (index1 >= 0) {
System.out.println("The indexes are " + index1 + " and " + index2 + "(Values " + myArray[index1] +
" and " + myArray[index2] + ")");
} else {
System.out.println("Not found");
}
}
}

Categories