Searching duplicates in 2 dimensional array - java

I have 2 dimensional array like :
{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}
How can I find the duplicate elements like '6', '46' and '50'?
My code finds consecutive duplicates:
for (int i = 0; i < a2.length; i++) {
for (int j = 0; j < a2[i].length; j++) {
cursor = a2[i][j];
if(j + 1 < a2[i].length){
if(cursor == a2[i][j + 1]){
System.out.println(cursor + "has duplicate in this array");
}
}
}
}

Iterate through all elements and save it in a temporary set.
When you encounter a duplicate, the list will contain it.
import java.util.HashSet;
import java.util.HashSet;
public class HelloWorld
{
public static void main(String[] args)
{
int[][] arr = {
{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}
};
HashSet<Integer> elements = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(elements.contains(arr[i][j])) {
duplicates.add(arr[i][j]);
}
elements.add(arr[i][j]);
}
}
System.out.println(duplicates.toString());
}
}
Output:
[50, 6, 10, 46]

Try this code:-
import java.util.Arrays;
import java.util.List;
public class ArrayTest {
public static void main(String[] args) {
Integer[][] myarray = new Integer[][]{
{ 10, 20, 30, 40 },
{ 50, 77, 60, 70 },
{ 33, 22, 88, 99 },
{ 21, 66, 65, 21 }
};
int i,j;
for(i=0;i<myarray.length;i++)
{
for(j=0;j<myarray.length;j++)
{
int temp= myarray[i][j];
myarray[i][j]=0;
List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(i));
Boolean b=rowvalues.contains(temp) ;
if(b==true)
{
System.out.println("duplicate at ["+i+"]["+j+"] is: "+temp);
}
myarray[i][j]=temp;
}
}
}
}

Related

Adding up all the elements of each column in a 2D array

So I have this dummy 2D array:
int mat[][] = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:
public void sum(int[][] array) {
int count = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
System.out.print(array[rows][columns] + "\t");
count += array[0][0];
}
System.out.println();
System.out.println("total = " + count);
}
}
Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?
One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.
public static void main(String[] args) {
int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
// Find maximum possible length of sub array
int maxLength = 0;
for (int i = 0; i < mat.length; i++) {
if (maxLength < mat[i].length)
maxLength = mat[i].length;
}
for (int i = 0; i < maxLength; i++) {
int sum = 0;
for (int j = 0; j < mat.length; j++) {
// Avoid if no value available for
// ith column from this subarray
if (i < mat[j].length)
sum += mat[j][i];
}
System.out.println("Sum of Column " + i + " = " + sum);
}
}
Use an ArrayList to get the sum of all the columns.
public static void sum(int[][] array) {
ArrayList<Integer> sums = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if (sums.size() <= column) {
sums.add(column, 0);
}
int curVal = sums.get(column);
sums.remove(column);
sums.add(column, curVal + array[row][column]);
}
}
for (int i = 0; i < sums.size(); i++) {
System.out.println("Sum of column " + i + " = " + sums.get(i));
}
}
Here is one alternative.
The supplied data.
int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
{ 15, 25, 35, 45 }, { 27, 29, 37, 48 },
{ 32, 33, 39, 50, 51, 89 }, };
First, find the maximum length of the array in which to store the sum.
int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);
Allocate the new array to hold the sums.
int[] sums = new int[max];
Now just use the Arrays.setAll method to sum them, taking careto not exceed the current array's length.
for (int[] arr : mat) {
Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}
System.out.println(Arrays.toString(sums));
Prints
[84, 107, 141, 183, 101, 149, 70, 80, 90]
You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:
int[][] matrix = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
int[] arr = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) -> IntStream
// iterate over the indices
// from 0 to maximum row length
.range(0, Math.max(row1.length, row2.length))
// summarize in pairs the elements of two rows
.map(i -> (i < row1.length ? row1[i] : 0) +
(i < row2.length ? row2[i] : 0))
// an array of sums
.toArray())
// the resulting array
.get();
System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]
See also:
• Sum of 2 different 2d arrays
• How to calculate the average value of each column in 2D array?
…and the same with lambda:
int[] array = Arrays.stream(mat)
.reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
.map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
: i < a1.length ? a1[i] : a2[i] ).toArray()).get();
gets the sums of each column in the int[] array:
[84, 107, 141, 183, 101, 149, 70, 80, 90]

distrubuting people to groups evenly based on userinput

ReadFile randomGenerate = new ReadFile();
Input userNum = new Input();
String classnum = userNum.fileToSelect();
int lineNumber = randomGenerate.lineCounter(classnum);
//number of students in classnum.txt
ArrayList<String> people = randomGenerate.readPeople();
//a string of names(first word on each row)
int userPut = userNum.numInput();
int maxNum = lineNumber/userPut;
Right not, I am reading off a txt file - the first word of each row which is the name of a person. I want to distribute this ArrayList of people into even groups, with the number of groups based on userinput.
int[] numbers = RandomNumbersWithoutRepetition(0, lineNumber, lineNumber);
//an array of numbers IN ORDER
int[] randomNumbers = RandomizeArray(numbers);
//shuffles the array
I generated a set of numbers in order, and then shuffled them, which works fine.
But, my method of grouping people has been based off ifelse conditions which don't work so well. So is there an efficient method to put this ArrayList of names into user-desired groups?
I have x number of students.
I have n number of groups.
I'm assuming there's no other criteria for dividing students into groups.
Basically, you divide the number of groups into the number of students. Yes, you have to deal with a remainder. But it's straightforward.
Here are the results of a test. I created 53 students and shuffled them. I then divided the students into 4 groups. I manually formatted the output to fit in the answer. Group 1 has 14 students, while the remaining groups have 13 students.
Students: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52,
47, 38, 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1,
2, 41, 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33,
25, 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
Group 1: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52, 47, 38
Group 2: 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1, 2, 41
Group 3: 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33, 25
Group 4: 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
And here's the code. The groupStudents and sortStudents methods are the methods that do the work.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentGroups {
public static void main(String[] args) {
int numberOfGroups = 4;
int numberOfStudents = 53;
StudentGroups sg = new StudentGroups(numberOfStudents);
sg.printStudents();
List<List<Integer>> groups = sg.groupStudents(
numberOfGroups);
sg.printGroups(groups);
}
private List<Integer> students;
public StudentGroups(int numberOfStudents) {
students = new ArrayList<>(numberOfStudents);
for (int i = 0; i < numberOfStudents; i++) {
students.add(i + 1);
}
Collections.shuffle(students);
}
public void printStudents() {
System.out.print("Students: ");
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
public List<List<Integer>> groupStudents(int groups) {
List<List<Integer>> output = new ArrayList<>();
int size = students.size();
int group = size / groups;
int remainder = size % groups;
sortStudents(output, size, group, remainder);
return output;
}
private void sortStudents(List<List<Integer>> output,
int size, int group, int remainder) {
List<Integer> list = new ArrayList<>();
int count = 0;
for (int i = 0; i < size; i++) {
list.add(students.get(i));
if (count == 0 && remainder > 0) {
if (group > 0) {
list.add(students.get(++i));
}
remainder--;
}
if (++count >= group) {
addList(output, list);
list = new ArrayList<>();
count = 0;
}
}
addList(output, list);
}
private void addList(List<List<Integer>> output,
List<Integer> list) {
if (list.size() > 0) {
output.add(list);
}
}
public void printGroups(List<List<Integer>> groups) {
for (int j = 0; j < groups.size(); j++) {
System.out.print("Group ");
System.out.print(j + 1);
System.out.print(": ");
List<Integer> students = groups.get(j);
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
}
}

Problems with insertion sort

I have tried to write an insertion sort algorithm, which I thought should have worked but it does not.
int [] array = {108, 10, 45, 67, 108, 23, 29, 108, 48, 67,902, 2, 32, 74, 108, 902};
for(out = 1; out < array.length; out++) {
min = array[out];
in = out - 1;
while(array[in] > min && in > 0) {
array[in + 1] = array[in];
in--;
}
array[in] = min;
}
The output I get when it is run:
32 45 45 45 45 48 67 74 108 108 108 108 902 902 902 902
The expected output is:
2, 10, 23, 29, 32, 45, 48, 67, 67, 74, 108, 108, 108, 108, 902, 902
Try this here
int[] array = {902, 902, 48, 108, 32, 45, 45, 67, 74, 108, 45, 45, 3, 108, 902, 108, 902};
for (int i = 1; i < array.length-1; i++) {
int x = array[i];
int j = i;
while (j > 0 && array[j-1] > x) {
array[j] = array[j-1];
j = j - 1;
}
array[j] = x;
}
System.out.println(Arrays.toString(array));
/**
* Insertion sort O(n^2)
* #author shohanur rahaman
*/
public class insertionSort {
public static void main(String args[]){
int[] ara = {5,32,99,0,6,-12,19};
for(int i=1;i<ara.length;i++){
int tmp = ara[i];
int j=i-1;
while(j>=0 && tmp<ara[j]){
ara[j+1] = ara[j];
j--;
}
ara[j+1] = tmp;
} // end parent loop
for(int i=0;i<ara.length;i++){
System.out.print(ara[i]+ " ");
}
}
}

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};

How do you sort numbers in ascending order from a for loop?

i have a for loop that multiples 3 and 7 by all numbers between 1 and 100. It only shows the numbers that are less the 100 after the multiplication though. How would you sort it so that its in ascending order?
for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}
would use another if statement to sort it?
How about:
for(int i = 1; i<=100; i++){
if(i % 3 == 0 || i % 7 == 0)
System.out.println(i);
}
This sounds like it'll do what you need:
[mike#mike ~]$ cat temp/SO.java
package temp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SO {
private static final int MAX_VAL = 100;
public static void main(String[] args) {
List<Integer> results = new ArrayList<Integer>();
for (int i = 1; i <= MAX_VAL; i++) {
int result1 = 3 * i;
int result2 = 7 * i;
if (result1 <= MAX_VAL) {
results.add(result1);
}
if (result2 <= MAX_VAL) {
results.add(result2);
}
}
Collections.sort(results);
System.out.println(results);
}
}
[mike#mike ~]$ javac temp/SO.java
[mike#mike ~]$ java temp.SO
[3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]

Categories

Resources