Hello I create a 2D array and i want to find the position from the first 2 in the array. And after to add the index in a new ArrayList. But this code doesn't work. Any idea for the problem?
import java.util.ArrayList;
class Test {
public static void main(String[] args) {
ArrayList<Integer> tableau = new ArrayList<Integer>();
int[][] tab = {
{1,1,1,1,1,1,2,1,1,2,1,1,1,2,1,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1},
};
for (int i = 0; i < tab.length; i++) {
int j = tab[i].indexOf(2);
for (int k = j ; k < tab[i].length; k++) {
if (tab[i][j] == 2){
tableau.add(j);
}
}
}
for (Integer row : tableau) {
System.out.println("row = "+ Arrays.toString(tableau));
}
}
}
As others have mentioned, regular arrays do not have an indexOf method, meaning that you will get an error when you compile.
However, you can easily create your own method to use as a substitute.
private static int indexOf(int value, int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] == value)
return i;
}
return -1;
}
Then you can just replace this line:
int j = tab[i].indexOf(2);
With this one:
int j = indexOf(2, tab[i]);
Related
I was trying to create a code that rearranges given elements in an array -by the user- in ascending order, and I have done that, but the program requires
printing the given elements after sorting them firstly, then printing them before sorting.
I have no problem with printing the elements after sorting
the problem is with printing them before sorting
how to re-use ar[S] = in.nextInt() the given elements by the user out of its for loop
import java.util.*;
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int ar[] = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
for (int i = 0; i < ar.length; i++) {
/* this nested for loop is used to compare the first element with the second one in the array
or the second element with the third.
*/
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
// I wanna do something like that
// System.out.println(ar[S]);
// but of course I cant cause array S is only defined in it's loop
}
}
You can't reuse it, you need to keep the original array stored in another array that stays untouched. Additionally, Arrays are usually declared as int[] ar in Java, instead of int ar[]. Something along the following lines should work as intended:
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int[] ar = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
System.out.println("::: Original Array :::");
int[] originalArray = Arrays.copyOf(ar, ar.length);
for (int j : originalArray) {
System.out.println(j);
}
System.out.println("::: Sorted Array :::");
for (int i = 0; i < ar.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
}
}
You can do a copy of the array using the copyOf method from the Arrays library (java.util.Arrays) before you start changing the array.
Here you can find some different approaches - https://www.softwaretestinghelp.com/java-copy-array/amp/
You can use System.out.print(Arrays.toString(arr)); to print the entire array.
public static void main(String... args) {
int[] arr = readArray(3);
System.out.print(Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
System.out.print(Arrays.toString(arr));
}
}
}
}
private static int[] readArray(int size) {
System.out.format("Enter %d elements:\n", size);
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for(itn i = 0; i < arr.length; i++)
arr[i] = scan.nextInt();
return arr;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Given the following code:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
break; //Preventing from counting duplicate times, is there way to replace this?
}
}
}
return count;
}
I would like to know if there is a solution which doesn't use break statement since I've heard its bad practice.
But without the break this method returns 6 instead of wanted 3 for array {'x', 'x', 'x'}.
If you're trying to find the number of unique elements in the array try using this approach as it has only one loop and hence efficient.
private static int findNUmberOfUnique(String[] array) {
Set<String> set=new HashSet<>();
for(int i=0;i<array.length;i++){
if(!set.contains(array[i])){
set.add(array[i]);
}
}
return set.size();
}
Let me know if I did not understand your requirement clearly.
You can always use a flag instead of break:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
boolean found = false;
for (int k = 0; k < a.length && !found; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
found = true;
}
}
}
return count;
}
You can use a hashmap to find the same elements in an array and preventing duplicate counting.
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer>hs=new HashSet<Integer>();
for(int i:nums1)
hs.add(i);
HashSet<Integer>hs1=new HashSet<Integer>();
for(int j:nums2){
if(hs.contains(j)){
hs1.add(j);
}
}
int[] res=new int[hs1.size()];
int j=0;
for(int k:hs1)
res[j++]=k;
return res;
}
}
I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;
public static int[][] copyMatrix(int[][] matrix)
{
for (int i = 0; (i < matrix.length); i++)
{
int[][] duplicateMatrix = new int[matrix.length][matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
hello all, this specific function doesnt seem to work since duplicateMatrix isnt initialized as a variable, but I cant seem to initialize since its being created in the loop, I cant find a way to generate the amount of cells need in a column.
help will be appreciated. thanks.
You should initialize the array before the loops, since you only want to initialize it once.
public static int[][] copyMatrix(int[][] matrix)
{
if (matrix.length < 1) {
return new int[0][0];
}
int[][] duplicateMatrix = new int[matrix.length][matrix[0].length];
for (int i = 0; (i < matrix.length); i++)
{
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
This code assumes that all the rows in your input array have the same number of elements (which is true for matrices).
You can relax this assumption if you remember that a 2-dimentional array is simply an array of arrays :
public static int[][] copyMatrix(int[][] matrix)
{
int[][] duplicateMatrix = new int[matrix.length][];
for (int i = 0; (i < matrix.length); i++)
{
duplicateMatrix[i] = new int[matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
A two-dimensional array is an array of arrays. You must first create the two-dimensional array, and then each one of its element individually:
public static int[][] copyMatrix(int[][] matrix)
{
int[][] duplicateMatrix = new int[matrix.length][];
for (int i = 0; (i < matrix.length); i++)
{
duplicateMatrix[i] = new int[matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
I need to sort in ascending order as I add object to my generic class (I'm using strings).
I'm using selection sort, but it is not working.
I don't know if it is the correct way of doing this, so would appreciate the input.
OrderSet class
public class OrderSet<T extends Comparable> implements Set<T> {
private T[] items;
private int size;
public OrderSet()
{
items = (T[]) new Comparable[5];
}
#Override
public void add(T s)
{
if(size >= items.length)
{
items = grow(items);
}
for(int i = 0; i < items.length; i++)
{
if(items[i] == null)
{
items[i] = s;
size++;
break;
}
}
if(size > 1)
{
for (int i = 0; i < size-1; i++)
{
for(int j = 1; j < size; j++)
{
T tmp;
if (items[i].compareTo(items[j]) > 0)
{
tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
}
}
#Override
public void show()
{
for(T a : items)
{
if(a != null)
System.out.print(a+", ");
}
}
public T[] grow(T[] a)
{
T[] newA = (T[]) new Comparable[a.length+5];
System.arraycopy(a, 0, newA, 0, a.length);
return newA;
}
}
main
public class Main {
public static void main(String[] args) throws IOException
{
OrderSet<String> s1 = new OrderSet<>();
WordCount s2 = new WordCount();
Scanner input = new Scanner("the boy plays in the park with dog");
while (input.hasNext())
{
String w = input.next();
s1.add(w);
}
s1.show();
System.out.println();
}
}
I think it's your Sort Algorithm that is wrong. Ardentsonata is right, you use a Bubblesort algorithm but there is a mistake:
for (int i = 0; i < size-1; i++) {
for(int j = 1; j < size; j++){
T tmp;
if (items[i].compareTo(items[j]) > 0) {
tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
The Problem is the start value of the second loop, you want to check if any other element - except the ones you already sorted is bigger than the element you want to sort at the moment.
So your second loop needs this head:
for(int j = (i+1); j < size; j++)
so you really sort the array.
Otherwise you were uncontrollable switching your values aroung, because after you switched something to the second slot you switch it back in the next iteration.
Hope that helps !
What you seem to be doing is a bubble sort as you add in items, the generic form of a selection sort is as follows:
for(int i = 0; i<arr.length - 1; i++)
{
int smallest = i;
for(int j = i + 1; j< arr.length; j++)
{
if(arr[j].compareTo(arr[smallest]) > 0)
smallest = j;
}
if(smallest < arr.length && smallest != i)
swap(arr[i], arr[smallest]);
}
You could do it swapping the largest into the last index, but this should work as well. Note, swap is just a placeholder psuedocode for the actual swapping.
Use java.util.TreeSet< T >, which implements SortedSet< T >.
It's better to use String compare concept in this case
class City {
public static void main (String args[])
{
int i,j;
String temp;
String s[] = new String[6];
for(i=0; i<6; i++)
s[i]=args[i];
for(i=0;i<6;i++){
for(j=0;j<6-i-1;j++){
if(s[j].compareTo(s[j+1])>0)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
for(i=0; i<6; i++)
{
System.out.println(s[i]);
}
}}