I have a 2D array which if filled like this .
1 2 0 0 0
1 2 0 0 0
0 0 3 4 5
0 0 3 4 5
0 0 3 4 5
another example
1 2 3 0
1 2 0 4
1 0 3 4
0 2 3 4
the code which I want to write is
searching about the maximum set of number repeated in the array .
in example 1 : the answer is 3 because the maximum is ( 3 4 5 ) repeted 3 times unlike ( 1 2 ) repeated just once .
Also in example 2, the maximum is 2 because you will not have the same set of numbers repeated more than two times .
I want to write a code for that .
any help ?!
Although this does not solve your issue directly, you can gather and count all sequences by assigning them as keys in a Map. After you do this, you can get the longest sequences and see which one has the highest frequency.
Output from Code Below
Sequence Frequency
-------- ---------
2 2
5 3
1,2 2
3,4,5 3 // <- Longest sequence, Highest frequency.
4,5 3
Sequence Frequency
-------- ---------
1 1
2 1
3 1
4 3 // <- Highest frequency, but not a sequence.
2,3,4 1
1,2 1
1,2,3 1
2,3 1
3,4 2 // <- Second highest frequency, is a sequence.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class MatrixSequenceFrequency {
public static void main(String[] args) {
int[][] arr1 = new int[][] {
{ 1, 2, 0, 0, 0 },
{ 1, 2, 0, 0, 0 },
{ 0, 0, 3, 4, 5 },
{ 0, 0, 3, 4, 5 },
{ 0, 0, 3, 4, 5 }
};
printSequences(findSequences(arr1));
int[][] arr2 = new int[][] {
{ 1, 2, 3, 0 },
{ 1, 2, 0, 4 },
{ 1, 0, 3, 4 },
{ 0, 2, 3, 4 }
};
printSequences(findSequences(arr2));
}
private static Map<String, Integer> findSequences(int[][] arr) {
Map<String, Integer> sequences = new HashMap<String, Integer>();
for (int i = 0; i < arr.length; i++) {
indexSequences(arr[i], sequences);
}
return sequences;
}
private static void indexSequences(int[] arr, Map<String, Integer> sequences) {
StringBuffer buff = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] != 0) {
buff.append(arr[j]).append(',');
} else {
break; // `0` breaks the sequence.
}
}
if (buff.length() > 0) {
if (buff.charAt(buff.length() - 1) == ',') {
buff.deleteCharAt(buff.length() - 1); // Remove extra comma.
}
Integer value = sequences.get(buff.toString());
sequences.put(buff.toString(), value == null ? 1 : value + 1);
buff.delete(0, buff.length()); // Clear Buffer
}
}
}
private static void printSequences(Map<String, Integer> sequences) {
String format = "%-10s %s%n";
System.out.printf(format, "Sequence", "Frequency");
System.out.printf(format, "--------", "---------");
for (Iterator<Entry<String, Integer>> it = sequences.entrySet().iterator(); it.hasNext();) {
Entry<String, Integer> entry = it.next();
System.out.printf(format, entry.getKey(), entry.getValue().toString());
}
System.out.println();
}
}
I would filter through the array and add each number that is the same to a variable and then display the variable with the most hits
int three = 0;
for (int i = 0; i < array.size(); i++){
if(array.get(i) == 3){
three++;
}else if(array.get(i) == "Some other number"){
number++;
}
then you would need to filter through the numbers you just added up so
Collections.sort(arrayList); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort
then i would sort through the Array as to see how many are the same
if(arrayList.size() - 1 == arrayList.size() - 2){
System.out.println(arrayList.size() - 1 " & " arrayList.size() - 2);
}
There would be a lot more tedious coding but this would be the foundation of your code you first add the values to the variable and sort through the array list to see what value appeared the most and you would need a 2D Array for adding the actual variables we made at the start then sort them highest to lowest.
Here use this program
public class Matrix {
public static void main(String[] args) {
int[][] a = new int[][] {
{ 1, 2, 3 },
{ 3, 3, 3 },
{ 1, 2, 3 }
};
int result = 0;
int largestNum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (result <= count(a[i][j], a)) {
result = count(a[i][j], a);
largestNum = a[i][j];
}
}
}
// Display the result
System.out.println("Largest Number: " + largestNum);
}
public static int count(int arrVal, int[][] a) {
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (arrVal == a[i][j]) {
count++;
}
}
}
return count;
}
}
For simplicity I have declared a 2d array of length 3 for both rows and columns. You can use array of any length
Related
I need to count how many rows does the user inputs that are only 0, something like:
Test 1
0 0 0
1 2 3
2 2 1
Test 2
1 2 3
0 0 0
0 0 0
Rows with only 0 values: 3
This is the code that reads the matrices:
final int rows = 3, cols = 3;
Scanner input = new Scanner(System.in);
System.out.println("Number of tests");
int n = input.nextInt();
int test[][][] = new int[n][rows][cols];
for (int i = 0; i < n; i++) {
System.out.println("Test " + (i + 1));
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
test[i][j][k] = input.nextInt();
}
}
}
You can get the number of zero rows in a 3D matrix using Streams as follows:
public static void main(String[] args) {
int[][][] test = {
{{0, 0, 0}, {1, 2, 3}, {2, 2, 1}},
{{1, 2, 3}, {0, 0, 0}, {0, 0, 0}}};
System.out.println(zeroRowsCount(test)); // 3
}
public static long zeroRowsCount(int[][][] arr3d) {
return Arrays.stream(arr3d)
// the number of zero rows in each 2D array
.mapToLong(arr2d -> zeroRowsCount(arr2d))
// total number of zero rows
.sum();
}
public static long zeroRowsCount(int[][] arr2d) {
return Arrays.stream(arr2d)
// filter those rows that consist of zeros
.filter(row -> Arrays.stream(row)
// all elements are zeros
.allMatch(i -> i == 0))
// the number of zero rows
.count();
}
I have this array :
int a[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 6, 3 }, { 8 }, { 7 } };
I want to print a new one up to 3 row :
{1,2,3},{4,5,6},{6,3}
public static int[][] cut(int arr[][], int n) {
// n : is up " up to which row ? " Here is n = 3
// FIRST STEP :
// COUNTING ELEMENTS
int counter = 0;
for (int row = 0; row < arr.length; row++) {
for (int column = 0; column < arr[row].length; column++) {
counter++;
}
System.out.println(counter);
counter = 0;
}
// PRINTS 3 3 2 1 1 : OK
// SECOND STEP : I only want up to 3 row so : 3 3 2
// CREATE AN EMPTY TWO DIMENSIONAL ARRAY but how ?
//I think that I should be using a loop for but I've no idea how
int be[][] = new int[n][];
for ( int i = 0; i < n ; i ++){
be[i][counter];
// This doesn't work, I know why but I don't have other suggestion :s
}
// THIRD STEP : Putting values in the new array
}
return be;
}
Thank you
Assign 1-D arrays of 2-D array, one by one one to the other 2-D array.
Demo-http://ide.geeksforgeeks.org/306eYp
For defining a two dimensional array you should modify the for-loop
for ( int i = 0; i < n ; i ++){
be[i] = new int[arr[i].lenght];
}
i am trying to solve some basic java question:
i have an array like int[] x = { 12, 24, 33 };. I need to break it into digits like {1, 2, 2, 4, 3 ,3} and then count the repeating numbers this way: 1:1, 2:2, 3:2, 4:1.
Until now i got this code but i can't save the digits into array.
Can some one help me ?
public class targil_2_3 {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
int[] ara = new int[x.length * 2];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < 2; j++) {
ara[j] = x[i] % 10;
x[i] = x[i] / 10;
System.out.println(ara[j]);
}
}
}
}
You dont need to store individual digits, you need to store just count for digits. Lets assume, that you're working with 10 based numbers, then code can looks like
public static void main(String[] args) {
int[] x = { 12, 24, 33, 0, 10, 555 };
int[] count = new int[10];
for (int i = 0; i < x.length; i++) {
int num = x[i];
if (num == 0) {
count[0]++;
continue;
}
while (num > 0) {
count[num % 10]++;
num = num / 10;
}
}
System.out.println(Arrays.toString(count));
}
Output is
[2, 2, 2, 2, 1, 3, 0, 0, 0, 0]
import java.util.Arrays;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class Use {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
Map<Integer, Long> result = Arrays.stream(x).boxed()
.map(String::valueOf)
.collect(joining())
.chars().boxed()
.collect(groupingBy(Character::getNumericValue, counting()));
System.out.println(result); //prints {1=1, 2=2, 3=2, 4=1}
}
}
Explanation
First line convert an int[] to a Stream<Integer> (for each element)
Convert Stream<Integer> to Stream<String>
Reduce the Stream<String> to String
Create a Stream<Integer> (for each digit)
Count the occurences of each digit in a Map
we have only 10 decimal digits from 0 to 9 , [0..9]
so we make an array with length 10 , like count :
int count[] = new int[10];
for(int i = 0 ; i < x.length ; i++){
if( x[i] == 0 ){
count[0]++;
continue;
}
while(x[i]!=0){
int index = x[i] % 10;
count[index]++;
x[i] /= 10;
}
}
then we will have the number of digits in count array , so we can print it :
for(int i = 0 ; i < 10 ; i++)
System.out.println(i+" : "+count[i]);
if your data is so big it is better to use Map
there are many ways to do this
Digits are 0-9. Build a counter array of size 10, and count each digit extracted in the proper index of the counter array ("counter[digit]++").
Edit: Of- course, in the end you can build the desired result array based on the counter array.
For example: result[0] = "0:" + counter[0];"
Good Luck!
I have the below code which is aimed at finding out a duplicate element in an array and printing it with its count.
I have used the below approach to solve the problem.
copy the original array into temp array
find the duplicates in original array and remove the same
copy the non duplicate array into another temp array
compare non duplicate array with original array and print out the duplicates with their counts.
For calculating the length I am using my own version of code.
It o/ps
5 4
2 3
which is correct but I want to know if we can still refine this code.
Please suggest best approach, condition is that there should not be any build in method/functions usage.
package codingpractice;
public class DuplicateCount {
public static void main(String argsp[]) throws Exception {
int array[] = { 5, 1, 2, 5, 3, 2, 2, 5, 5 };
DuplicateCount hw = new DuplicateCount();
int length = hw.length(array);
hw.duplicates(array, length);
}
public void duplicates(int array[], int length) throws Exception {
int end =length, dupCount = 0;
//copying to another array for later comparison
int[] aarray = new int[length];
for (int i = 0; i < end; i++) {
aarray[i] = array[i];
}
//finding duplicates and removing the same
for (int i = 0; i < end; i++) {
for (int j = i + 1; j < end; j++) {
if (array[i] == array[j]) {
int shiftLeft = j;
for (int k = j + 1; k < end; k++, shiftLeft++) {
array[shiftLeft] = array[k];
}
end--;
j--;
}
}
}
//copying non duplicates to another array
int[] tarray = new int[end];
for (int i = 0; i < end; i++) {
tarray[i] = array[i];
}
//Printing duplicates and there counts, comparing original array and non duplicate array
for (int i = 0; i < length(tarray); i++) {
dupCount = 0;
for (int j = 0; j < length; j++) {
if (tarray[i] == aarray[j]) {
dupCount++;
}
}
if (dupCount > 1) {
System.out.println(tarray[i] + " " + dupCount);
}
}
}
//length of array- not using inbuild function
int length(int array[]) throws Exception {
int count = 0;
int temp = 0;
try {
while (true) {
count++;
temp = array[count];
}
} catch (Exception e) {
return count;
}
}
}
Much easier technique:
Map<Integer, Integer> map = new HashMap<>();
for (int i : array) {
Integer count = map.get(i);
if (count == null) {
map.put(i, 1);
}
else {
map.put(i, count.intValue() + 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
For the fun of it, here's a Java 8 equivalent:
Map<Integer, Integer> map = new HashMap<>();
for (int i : array) {
map.compute(i, (k, v) -> (v == null) ? 1 : v + 1);
}
map.entrySet().stream()
.filter(e -> e.getValue() > 1)
.forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));
The map.compute() call could also be replaced by
map.merge(i, 1, Integer::sum);
Just to complement JB Nizet's Java 7 solution. Here is a Java 8 solution:
public static void main(final String[] args) throws Exception {
final int[] ints = {1, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 0, 0, 0};
final Map<Integer, Integer> count = IntStream.of(ints).
boxed().collect(HashMap::new, (map, i) -> {
map.merge(i, 1, (j, k) -> j + k);
}, HashMap::putAll);
//to print out
count.forEach((i, c) -> {System.out.println( i + " has a count of " + c);});
}
Output:
0 has a count of 3
1 has a count of 2
2 has a count of 1
3 has a count of 2
4 has a count of 2
5 has a count of 1
6 has a count of 1
7 has a count of 1
8 has a count of 1
9 has a count of 1
Using indices, create an empty array. Run on your array and increase the corresponding value at the index each time you run on it.
In your example:
int[] source = { 5, 1, 2, 5, 3, 2, 2, 5, 5 };
int[] counts = new int[6];
for (int i : source) {
counts[i]++;
}
Then your can run on the counts and you will get each element (array index) and its count (array value).
Given the array, i need to find how many monotonically increasing Sub-arrays there are in that array?
For example, with [0, 1, 3, 1 , 2] - has 2 monotonical sub-arrays : [0, 1,3] and [1,2].
public class SUB_ARRAY {
public static void main(String a[]){
int[] x = new int[6];
x[0]=1;
x[1]=2;
x[2]=3;
x[3]=6;
x[4]=9;
x[5]=10;
ArrayList<Object> arraylist = new ArrayList<Object>();
HashSet list = new HashSet();
for ( int i=0; i< (x.length -1); i++){
if (x[i+1]> x[i] ){
list.add(x[i]);
list.add(x[i+1]);
} else if (x[i+1] < x[i] || x[i+1]==x[i]) {
arraylist.add(list.clone());
list.clear();
}
}
System.out.println(arraylist.size());
}
}
The output is : 0 (instead of 1).
So, where I'm wrong?
Check out this solution. It now only displays the counter but print you the subarrays. If you need only the continues subarrays you can easily modify it.
As you see I use neither HashSet nor ArrayList for storing temporary data just a counter.
import java.util.ArrayList;
public class SUB_ARRAY{
public static int SUBARRAY_MINIMUM_LENGTH = 2;
public static void main(String a[]){
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(5);
x.add(0);
x.add(1);
x.add(3);
x.add(4);
x.add(2);
x.add(3);
x.add(6);
x.add(1);
x.add(0);
x.add(4);
int monoton = 0;
int changed = -1;
System.out.println("Initial array: " + x.toString());
for ( int i=0; i< x.size() -1; ++i){
if (x.get(i+1) > x.get(i)){
if (changed > -1){
for (int j = changed; j <i+2; ++j){
monoton += checkSubArray(x, j, i+2);;
}
}
else{
System.out.println("New monoton subarray start index: " + i + " value: " + x.get(i));
changed = i;
monoton += checkSubArray(x, changed, i+2);
}
}
else if (changed > -1){
changed = -1;
}
}
System.out.println("Monoton count: " + monoton);
}
private static int checkSubArray(ArrayList<Integer> x, int start, int end)
{
if (end-start < SUBARRAY_MINIMUM_LENGTH){
return 0;
}
for (int subi = start; subi < end; ++subi){
System.out.print(" " + x.get(subi));
}
System.out.println();
return 1;
}
}
The output will be the following
Initial array: [5, 0, 1, 3, 4, 2, 3, 6, 1, 0, 4]
New monoton subarray start index: 1 value: 0
0 1
0 1 3
1 3
0 1 3 4
1 3 4
3 4
New monoton subarray start index: 5 value: 2
2 3
2 3 6
3 6
New monoton subarray start index: 9 value: 0
0 4
Monoton count: 10