I am taking the size of an array in a variable in a loop. Each time I have to assign the size of the array equal to that variable and then take integers equal to that size. For example:
for(i = 0; i < N; i++)
{
variable = sc.nextInt();
int []array = new int[variable];
for(j = 0; j < variable; j++)
{
array[j] = sc.nextInt();
}
}
Please provide me the most efficient method as I am new to java :)
Maybe you need something like this :
List<int[]> list = new ArrayList<>();//create a list or arrays
for (int i = 0; i < n; i++) {
int variable = sc.nextInt();
int[] array = new int[variable];
for (int j = 0; j < variable; j++) {
array[j] = sc.nextInt();
}
list.add(array);//add your array to your list
}
You can create a list of arrays and initialize them on outer loop and add values to arrays using position i and j.
// initialize list with n, though you can also use 2D array as well
List<int[]> array = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
variable = sc.nextInt();
// create an array and add it to list
array.add(new int[variable]);
for (int j = 0; j < variable; j++) {
// fetch the array and add values using index j
array.get(i)[j] = sc.nextInt();
}
}
for(i=0;i<N;i++)
{
variable = sc.nextInt();
ArrayList array = new ArrayList(variable)
for(j=0;j<variable;j++)
{
int input = sc.nextInt()
array.add(input);
}
}
If an ArrayList works, this is how I'd do it.
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;
}
So I'm trying to make a program that counts the occurences of int in an array. what i tried to do is to make a method that lists the unique integers, then another method to compare the list items to the original array items.
public List listUnique(int[] arr){
Arrays.sort(arr);
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
}
return temp;
}
public int[] countDupli(List unique, int[] arr){
int [] ret = new int[unique.size()];
Iterator <Integer> iterator = unique.iterator();
for (int l = 0; l < unique.size(); l++){
ret[l] = iterator.next().intValue();
}
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
for (int k = 0; k < ret.length; k++){
for (int i = 0; i < arr.length; i++){
if ( ret[k] == arr[i]){
dupli[k]+= 1;
}
}
k++;
}
return dupli;
}
It isn't doing what is intended to do tho. For example, an input of {1,2,...,1,2} 10 items of those, prints the correct unique items but only outputs the count of 1 but not 2. dupli = [5,0]. where did the algorithm go wrong? thanks
In your code try debugging or just print ret[] values and see if all unique values are present.
Other Suggestions:
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
You can simply use HashSet, then you don't have to write above code to find unique values. HashSet does not store duplicate values.
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
Then you can use iterator and compare with your sorted array and increase count simultaneously.
You can skip the following for loop, as java initializes it to 0 by default.
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
I am trying to implement kmeans algorithm for a certain Music Recommendation System in Java.
I have generated 2 arrays,playsFinal[](the total play-count of an artist by all users in the dataset) and artFinal[] (the unique artists in the entire dataset) . The playcount of every artFinal[i] is playsFinal[i]. For k,I have chosen kclusters=Math.sqrt(playsFinal.length)/2.
I have an array clusters[kclusters][playsFinal.length] and the first position clusters[i][0] for every 0<i<kclusters is filled with a certain value,which is basically the initial mean as in kmeans algorithm.
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
Here,weight[] is a certain score given to every artist.
Now,in the following function I am returning the index,ie,which cluster the plays[i] should be added to.
public static int smallestdistance(double a, double[][] clusters) {
a = (double) a;
double smallest = 0;
double d[] = new double[kclusters];
for (int i = 0; i < kclusters; i++) {
d[i] = a - clusters[i][0];
}
int index = -1;
double d1 = Double.POSITIVE_INFINITY;
for (int i = 0; i < d.length; i++)
if (d[i] < d1) {
d1 = d[i];
index = i;
}
return index;
}
If not obvious,I am finding the minimum distance between playsFinal[i] and the initial element in every clusters[j][0] and the one that is the smallest,I am returning its index (kfound). Now at the index of the clusters[kfound][] I want to add the playsFinal[i] but here is where I am stuck. I can't use .add() function like in ArrayList. And I guess using an ArrayList would be way better. I have gone through most of the articles on ArrayList but found nothing that could help me. How can I implement this using a multidimensional ArrayList?
Thanks in advance.
My code is put together as follows:
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
double[] weighty = new double[artFinal.length];
for (int i = 0; i < artFinal.length; i++) {
weighty[i] = (playsFinal[i] * 10000 / playsFinal.length);
}
n = playsFinal.length;
kclusters = (int) (Math.sqrt(n) / 2);
double[][] clusters = new double[kclusters][playsFinal.length];
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
int kfound;
for (int i = 0; i < playsFinal.length; i++) {
kfound = smallestdistance(playsFinal[i], clusters);
//HERE IS WHERE I AM STUCK. I want to add playsFinal[i] to the corresponding clusters[kfound][]
}
}
public static int smallestdistance(double a, double[][] clusters) {
a = (double) a;
double smallest = 0;
double d[] = new double[kclusters];
for (int i = 0; i < kclusters; i++) {
d[i] = a - clusters[i][0];
}
int index = -1;
double d1 = Double.POSITIVE_INFINITY;
for (int i = 0; i < d.length; i++)
if (d[i] < d1) {
d1 = d[i];
index = i;
}
return index;
}
Java's "multidimensional arrays" are really just arrays whose elements are themselves (references to) arrays. The ArrayList equivalent is to create a list containing other lists:
List<List<Foo>> l = new ArrayList<>(); //create outer ArrayList
for (int i = 0; i < 10; i++) //create 10 inner ArrayLists
l.add(new ArrayList<Foo>());
l.get(5).add(foo1); //add an element to the sixth inner list
l.get(5).set(0, foo2); //set that element to a different value
Unlike arrays, the lists are created empty (as any list), rather than with some specified number of slots; if you want to treat them as drop-in replacements for multidimensional arrays, you have to fill them in manually. This implies your inner lists can have different lengths. (You can actually get "ragged" multidimensional arrays by only specifying the outer dimension (int[][] x = new int[10][];), then manually initializing the slots (for (int i = 0; i < x.length; ++i) x[i] = new int[i]; for a "triangular" array), but the special syntax for multidimensional array creation strongly predisposes most programmers to thinking in terms of "rectangular" arrays only.)
I am trying to put the values (integers) from the 2 dimensional array prices[][] into the cost variable of the objects in the array seatArray[][]. I think the problem is that I am trying to put the values from the prices array into nothing because the seatArray array is only full of object references to null. How would I go about fixing this?
line that calls constructor:
SeatChart seatArray = new SeatChart(givenArray);
constructor method:
public SeatChart(int[][] prices)
{
Seat[][] seatArray = new Seat[9][10];
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 10; j++)
{
seatArray[i][j].cost=prices[i][j];
}
}
}
Seat[][] seatArray = new Seat[9][10];
This just declares the array and doesn't initialize the array elements with Seat objects.
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 10; j++)
{
// I've used a default Seat() constructor to create the object, in your actual case, it may differ.
seatArray[i][j] = new Seat(); // Initializing each array element with a new Seat object
seatArray[i][j].cost=prices[i][j];
}
}
seatArray[i][j] = new Seat();
seatArray[i][j].cost= prices[i][j];
Or maybe for clarity
Seat seat = new Seat();
seat.setCost(prices[i][j]);
seatArray[i][j] = seat;
I want to make a loop on Two-dimensional array in Java.
How I do that? I wrote:
for (int i = 0; i<=albums.size() - 1; i++){
for (int j = 0; j<=albums.size() - 1; j++){
But it didn't work. Thanks.
Arrays have a read-only field called length, not a method called size. A corrected loop looks like this:
for(int i = 0; i < albums.length; i++ ) {
for (int j = 0; j < albums[i].length; j++) {
element = albums[i][j];
You have to recognize that a 2-D array is just an array whose element type happens to be another array. So the i loop iterates over each element in albums (which is an array) and the j loop iterates over that child array (with a potentially different size).
A more transparent way would be like this:
String[][] albums;
for(int i = 0; i < albums.length; i++ ) {
String[] childArrayAtI = albums[i];
for (int j = 0; j < childArrayAtI.length; j++) {
String element = childArrayAtI[j];
}
}
Try this if you are working with Java 1.5+:
for(int [] album : albums) {
for(int albumNo : album) {
System.out.print(albumNo + ", ");
}
System.out.println();
}
First of all, a two-dimensional array looks like this in Java:
int[][] albums = new int[10][10];
Now, for iterating over it:
for (int i = 0; i < albums.length; i++) {
for (int j = 0; j < albums[i].length; j++) {
int value = albums[i][j];
}
}