How to reduce copy-pasting? - java

If I have a number of similar classes, say:
Integer i0;
Integer i1;
Integer i2;
Integer i3;
Integer i4;
Integer i5;
Integer i6;
Integer i7;
Integer i8;
Integer i9;
And wanted to avoid doing this:
i0 = 0;
i1 = 1;
i2 = 2;
i3 = 3;
i4 = 4;
i5 = 5;
i6 = 6;
i7 = 7;
i8 = 8;
i9 = 9;
I'm thinking of doing something similar to this to achieve the same result:
int cnt = 0;
for(classname : arrayOfClassNames {
classname = cnt++;
}
How do I do that?
[clarification] I appears I was misunderstood. I was thinking more along the lines of having 10 separate classes still, not one array having 10 items.

Use an array or an ArrayList?
// using an array
Integer[] ints = new Integer[10];
for (int i = 0; i < 10; i++) {
ints[i] = i;
}
// using an array list
ArrayList<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
ints.add(i);
}
Following on from your update, what you are looking to do can be achieved using
Class.forName(classname).newInstance();
However, I would suggest that whatever you save in time to code it, you will lose in readability and ease of maintenance, so you may find this a false economy.

Store them in an array:
Integer[] array = new Integer[10];
for(int i = 0 ; i < 10 ; i++){
array[i] = i ;
}
To get i9: array[9]

Use a java.util.Map<T, K>:
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < 10; i++)
{
map.put("i" + i, i);
}
System.out.println(map);
System.out.println("i8: " + map.get("i8"));

A number of similar classes sounds like you want an Array:
Integer[] manyI = new Integer[] {0, 1, 2, ....};
Or you fill the Array with a loop:
Integer[] manyI = new Integer[10];
for (int i = 0; i < manyI.length; i++) manyI[i] = i;

Related

Map the values of array elements

public class EconomicModel {
public static void main(String[] args) {
int[] StarTime = new int[20];
int[] duration = new int[40];
int[] TotalDuration = new int[40];
int[] EndTime = new int[StarTime.length];
int[] relinqtime = new int[20];
int[] ResAllocRAM = {101,9,56,89,43,30,8,60,13,41,60, 20, 32,71,76,7,31,46,30,99 };
StarTime[0] = 0;
ExponentialDistribution exp = new ExponentialDistribution(4.0);
for(int j = 1; j < 20; j++){
StarTime[j] = (int)exp.sample() + 1+StarTime[j-1];
}
for(int k = 0; k < 20;k ++){
duration[k] = 20 + (int)(Math.random() * ((120 - 10) + 1));
}
for(int k = 0; k < 20; k++){
EndTime[k] = StarTime[k] + duration[k];
}
Random r = new Random();
for (int i=0; i<20; i++){
relinqtime[i] = r.nextInt((EndTime[i] - StarTime[i])+ StarTime[i] ) + StarTime[i];
}
for ( int j = 0; j<20; j++)
for(int k = StarTime[j]; k <= relinqtime[j]; k++){
TotalDuration[k]+= ResReqRAM[j];
}
}
}
I have arrays called StarTime, relinqtime, ResAllocRAM and TotalDuration. I want to assign values to the indexes of array TotalDuration based on the other three arrays. Like if value of StarTime[1] is 5, value of relinqtime[1] is 8, value of ResAllocRAM[1] is 9. I want that value TotalDuration[5],TotalDuration[6],TotalDuration[7] should be the value of ResAllocRAM[1].
I tried the above code but it is giving exception bound error at line TotalDuration[k]+= ResReqRAM[j];
What should I do to map the values of these arrays and produce a new array as mentioned?
Use a Map, it saves elements as Key, Value pair, remember keys should be unique.
Map<Integer, Integer> hashMap = new HashMap<>();
hashMap.put(TotalDuration[5], ResAllocRAM[1]); //put(key,value)
int value = hashMap.get(TotalDuration[5]); //it will return you value of ResAllocRAM[1]
simple tutorial for map
Try changing the line as follows
TotalDuration[k] = ResReqRAM[j];
If you are trying to increment TotalDuration then set initial values to 0 as the TotalDuration array is empty when you are trying to assign in it

Storing digits of numbers in array

Hello fellow programmers !
I am a beginner with Java and i am looking for a method or a way maybe to store the digits of a 6 digit number entered by the user , in an int array.
For example :-
if the number is 675421.
then i want to store the digits in an array like :-
int[] array = new int[6];
int number = 675421
array[0] = 6;
array[1] = 7;
array[2] = 5;
array[3] = 4;
array[4] = 2;
array[5] = 1;
I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!
Here you go,
String temp = Integer.toString(number);
int[] num = new int[temp.length()];
for (int i = 0; i < temp.length(); i++){
num[i] = temp.charAt(i) - '0';
}
for (int i = 0; i < temp.length(); i++) {
System.out.println(num[i]);
}
Edit, after comment
Here, First, you are converting to your number to a string.
Then, take each char out of it(in the loop), subtract the ASCII value of 0 from each char to get the digit [ie, ASCII of 0 is 48, 1 is 49, ... ] (see ASCII table)
Do something like this:
String number = "123123";
int[] intArray = new int[number.length()];
for (int i = 0; i < number.length(); i++)
{
intArray[i] = Integer.parseInt(Character.toString(number.charAt(i)));
}
Hope this helps,
Jason.
Below is the recursive solution
public static void main(String[] args) {
int testNum = 675421;
List<Integer> digitList = new ArrayList<Integer>();
collectDigits(testNum, digitList);
Object[] resultArr = digitList.toArray();
int listSize = resultArr.length;
for (int listCount = 0; listCount < listSize; listCount++) {
System.out.println("result["+listCount+"] = "+resultArr[listCount]);
}
}
private static void collectDigits(int num, List<Integer> digits) {
if (num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
One way to do this would be to turn the original integer into a string.
Loop over the string, parsing each character back to an int, and place into the array. Here is an example:
int number = 123456;
String strNumber = number+"";
int[] array = new int[strNumber.length()];
int index = 0;
for(char c : strNumber.toCharArray()){
array[index++] = Integer.parseInt(c+"");
}
System.out.println(Arrays.toString(array));
Math solution, you can split the int number using this:
int[] array = new int[6];
int number = 675421;
array[0] = ((number/100000)%10);
array[1] = ((number/10000)%10);
array[2] = ((number/1000)%10);
array[3] = ((number/100)%10);
array[4] = ((number/10)%10);
array[5] = ((number/1)%10);
If the "number" has a variable length you can automate this, write a coment if you need help

Merge Sort - Sorting String Array with Int Array

For this project, I'm given an array of strings and an array of ints. int[1] is the ranking for string[1]. I need to sort the int array in order from 1 to n using mergesort, which I've done below. But I also need to switch the positions of the string array when the int array gets moved so they are both sorted, if that makes sense? I can't figure out what's wrong with my coding or even if my idea will actually work, but I keep getting an array index out of bounds error on stringSorted[k] = stringRight[j] and I can't figure out if there's a way to fix this. Essentially, when an int was added to the sortedInt array, I also added that element to the sorted String array. Thank you for any help, and let me know if something doesn't make sense
private static int sortAndCount(int intToSort[]){
int inversionsLeft;
int inversionsRight;
int inversionsMerged;
if(intToSort.length == 1){
return 0;
}
int m = intToSort.length/2;
int[] intLeft = new int[m];
stringLeft = new String[m];
int[] intRight = new int[intToSort.length-m];
stringRight = new String[intToSort.length-m];
for (int i=0; i < m; i++){
intLeft[i] = intToSort[i];
stringLeft[i] = stringToSort[i];
}
for (int i = 0;i < intRight.length; i++){
intRight[i] = intToSort[m+i];
stringRight[i] = stringToSort[m+i];
}
inversionsLeft = sortAndCount(intLeft);
inversionsRight = sortAndCount(intRight);
intSorted = new int[intToSort.length];
stringSorted = new String[stringToSort.length];
inversionsMerged = mergeAndCount(intLeft, intRight);
return(inversionsLeft + inversionsRight + inversionsMerged);
}
private static int mergeAndCount(int[] intLeft, int[] intRight){
int count = 0;
int i = 0;
int j = 0;
int k = 0;
while(i < intLeft.length && j < intRight.length){
if(intLeft[i] < intRight[j]){
intSorted[k] = intLeft[i];
stringSorted[k] = stringLeft[i];
i++;
}
else{
intSorted[k] = intRight[j];
stringSorted[k] = stringRight[j];
count += intLeft.length - i + 1;
j++;
}
k++;
}
while (i < intLeft.length)
{
intSorted[k] = intLeft[i];
stringSorted[k] = stringLeft[i];
k++;
i++;
}
while (j < intRight.length)
{
intSorted[k] = intRight[j];
stringSorted[k] = stringRight[j];
j++;
k++;
}
return count;
}
}
int[] intLeft = new int[m];
stringLeft = new String[m];
int[] intRight = new int[intToSort.length-m];
stringRight = new String[intToSort.length-m];
You'll notice here that for the int arrays you are creating new variables, for the string you are replacing the outer. This is making your string arrays smaller with each recursive call whereas your int arrays are passed to each method.
By the time you get to calling mergeAndCount, stringLeft and stringRight are very small whereas the appropriately sized intLeft and intRight are passed as arguments.

Java Logical Array Trouble

I am trying to make an Array so that it contains 10 different integers 0-9.
I have this:
for (int i = 0; i < perm.length; i++)
{
int num = (int) (Math.random() * 9);
boolean check = true;
if (Arrays.asList(perm).contains(num) == true)
check = false;
else
{
check = true;
perm[i] = num;
}
while (check == false)
{
num = (int) (Math.random() * 9);
}
}
It seems that it should work and make an array with different integers, but it does not.
If you want to avoid creating a List you can just shuffle yourself :
Random random = new Random();
int[] perm = new int[10];
for (int i = 0; i < 10; i++) {
perm[i] = i;
}
for (int i = 0; i < 9; i++) {
int j = random.nextInt(10 - i);
int tmp = perm[i];
perm[i] = perm[i + j];
perm[i + j] = tmp;
}
System.out.println(Arrays.toString(perm));
How about this instead (if you want a more concise approach):
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
l.add(i); // add 0-9
Collections.shuffle(l)
Integer[] ints = l.toArray(new Integer[10]);
All we're doing here is creating a list, filling it with the integers 0-9, shuffling it, and writing the contents to an array.
If you want a more 'manual' approach, I'd suggest something like this:
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
l.add(i); // add 0-9
int[] ints = new int[10];
for (int i = 0 ; i < 10; i++)
ints[i] = l.remove((int)(Math.random() * l.size()));
System.out.println(Arrays.toString(ints));
[7, 2, 3, 4, 9, 6, 0, 1, 8, 5]
I'm assuming that you're allowed to use lists, since the code you posted includes a call to Arrays.asList.
It sounds like you're trying to generate a permutation of the numbers from 0 to 8 (9?). The easiest way to do this is to fill an array list with the numbers in sequence, and then use Collections.shuffle().

How divide 2d array into 1d array by one statement?

If I have:
int[] a = {1,2,3,4,5};
int[] b = {5,7,8,9};
int[][] array2d ={a,b};
I can divide array2d into 2 1d array by:
int[] A = new int[array2d[0].length];
int[] B = new int[array2d[1].length];
for(int i = 0; i < array2d.lenght; i++){
A[i] = array2d[i][0];
B[i] = array2d[i][1];
}
but can it be done by one statement?
For example if I have:
int[][] array2dx = new int[2][1000];
I can do easy:
int[] Ax = array2dx[0];
int[] Bx = array2dy[1];
So I am look for something similar (dividing into 2 arrays) for array int[1000][2];
but can it be done by one statement?
Not with any built-in methods that I'm aware of. It sounds like you basically want to write a transpose method though:
static int[][] transpose(int[][] input) {
// TODO: Validation. Detect empty and non-rectangular arrays.
int[][] ret = new int[input[0].length][];
for (int i = 0; i < ret.length; i++) {
ret[i] = new int[input.length];
}
for (int i = 0; i < input.length; i++) {
for (int j = 0; i < ret.length; j++) {
ret[j][i] = input[i][j];
}
}
return ret;
}
Once you've transposed an int[1000][2] into an int[2][1000] you can get the two int[1000] arrays out simply, as you've already shown.

Categories