Bank identification number validator - java

I'm new to objective-c and I don't understand Java very well, my question:
I have this code in Java that verifies the Bank identification number:
public static boolean isValidNIB(String nib) {
char[] toValidate = nib.substring(0, 19).toCharArray();
Integer checkDigit = Integer.valueOf(nib.substring(19));
Integer[] wi = { 73, 17, 89, 38, 62, 45, 53, 15, 50, 5, 49, 34, 81, 76, 27, 90, 9, 30, 3 };
Integer sum = 0;
for (int i = 0; i < 19; i++) {
sum += Character.digit(toValidate[i], 10) * wi[i];
}
return checkDigit.equals(98 - (sum % 97));
}
I need to convert this code into objective-c, the problem is that I can't make It work...
Here is my attempt to translate the java code into objective-c:
NSString *nib = #"003500970000199613031"; //UNICEF NIB :P
//transforms nsstring to array of chars
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[nib length]];
for (int i=0; i < [nib length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%C", [nib characterAtIndex:i]];
[chars addObject:ichar];
}
NSLog(#"array nib = %#",chars);
//retrieves the first 19 chars
NSMutableArray *toValidate = [[NSMutableArray alloc] init];
for (int i=0; i < chars.count; i++) {
if (i <= 19) {
[toValidate addObject:[chars objectAtIndex:i]];
}
}
NSLog(#"array toValidate = %#",toValidate);
NSString * checkDigit = [nib substringWithRange:NSMakeRange(19, 1)];
NSArray *weight = [NSArray arrayWithObjects:#"73", #"17", #"89", #"38", #"62", #"45", #"53", #"15", #"50", #"5", #"49", #"34", #"81", #"76", #"27", #"90", #"9", #"30", #"3", nil];
NSInteger sum = 0;
for (int i = 0; i < weight.count ; i++) {
sum += [[toValidate objectAtIndex:i] integerValue] * [[weight objectAtIndex:i] integerValue];
}
if (checkDigit.integerValue == (98 -(sum % 97))) {
NSLog(#"VALD");
}else{
NSLog(#"NOT VALID");
}
I'm sure that this is not the correct approach but It's something.
Thanks in Advance.

There is at least one error. Your
NSString * checkDigit = [nib substringWithRange:NSMakeRange(19, 1)];
returns only one character (at position 19) from the identification number (in this case
"3"), but
Integer checkDigit = Integer.valueOf(nib.substring(19));
computes the value of the substring starting at position 19 (in this case: "31").
Therefore the calculated checksum does not match the expected value.
But there is also a lot of unnecessary computations in your code, and there is
no reason to store the weights in an array of strings.
The method can be shortened to:
NSString *nib = #"003500970000199613031";
int weight[] = { 73, 17, 89, 38, 62, 45, 53, 15, 50, 5, 49, 34, 81, 76, 27, 90, 9, 30, 3 };
NSInteger sum = 0;
for (int i = 0; i < 19; i++) {
sum += [[nib substringWithRange:NSMakeRange(i, 1)] intValue] * weight[i];
}
int checkDigit = [[nib substringFromIndex:19] intValue];
if (checkDigit == (98 - (sum % 97))) {
NSLog(#"VALID");
} else {
NSLog(#"NOT VALID");
}
And the output is "VALID".

Related

I am getting java.lang.ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException
(2 answers)
Closed 4 years ago.
I am getting an array out of marks from this section, this section calculates the total mark by multiplying the weight of each assessment by the marks of each assessment. Any marks that gets a -1 is automatically set as 0 and not counted.
public double totalMark(){
int [] assessments = {2,2,2,2,1,1,1,1,2,2,1,3,70}; //Weight of each assessment
int totalMark = 0;
int overallmark = 0;
for (int i : marks) //marks of each assignment
if (marks[i] == -1) {
assessments[i] = 0;
}
for (int i : marks) {
totalMark =+ assessments[i] * marks[i];
}
for (int i : assessments) {
overallmark =+ assessments[i];
}
return totalMark/overallmark;
}
This is my main method:
public static void main(String args[]) {
int[] samsMarks = {50, 60, 65, 60, 65, 70, 55, 66, 60, 73, 65, 45, 68, 54};
int[] billysMarks = {50, 60, -1, 60, 65, 70, 55, 66, 60, 73, 65, 45, 68, 54};
Student sam = new Student("1111111", samsMarks);
Student billy = new Student("1111112", billysMarks);
System.out.println(billy.totalMark);
}
Replace all your
for (int i : marks)
with
for (int i = 0; i < marks.length; i++)
and
for (int i : assessments)
with
for (int i = 0; i < assessments.length; i++)
When you use
for (int i : marks)
i is not the index of marks but the elements that marks contains:
50, 60, 65, 60, 65, 70, 55, 66, 60, 73, 65, 45, 68, 54
As mentioned in the first answer you are using the for in this way:
for(element : list)
but since you need the index you should use it in the following form
for(initialization; termination; increment)
also a suggestion for the code instead of doing 3 loops through the element i suggest you do it in one iteration and you code can be as the following(since the number of element of both marks and assignment are the same)
for (int i = 0; i < marks.length; i++) {
if (marks[i] == -1) {
assessments[i] = 0;
}
totalMark =+ assessments[i] * marks[i];
overallMark =+ assessments[i];
}
You are iterating assessments array with a marks iterator and they might not be the same length. Check that.
These 2 loops are very problematic (both are accessing assessments and worry only about marks length:
for (int i : marks) //First problematic loop
if (marks[i] == -1) {
assessments[i] = 0;
}
for (int i : marks) { //Second problematic loop
totalMark =+ assessments[i] * marks[i];

searching in 2d array as O(n) with unsorted rows

I need to write a method that takes 2d array 'int [][] m' and a value 'val' and check if val is in the array in the complexity of O(n) while n defined as the number of rows and m must be squared
The array that can use as a parameter for my method must return true for this method:
(if it returns true so the array is as requested)
public static boolean test(int[][] m) {
int n = m.length;
for (int r = 0; r < (n - 1); r++)
for (int c = 0; c < n; c++)
for (int i = 0; i < n; i++)
if (m[r][c] > m[r + 1][i]) return false;
return true;
}
This array returns TRUE:
int [][] arr3 = new int [][]{
{ 0, 2, 1, 2, 0, 5, 5, 5, },
{ 21, 21, 7, 7, 7, 21, 21, 21 ,},
{ 21, 21, 21, 21, 21, 21, 21 , 21, },
{ 21, 21, 23 , 42, 41, 23, 21, 21, },
{ 60 ,56, 57, 58, 53, 52, 47, 51 ,},
{ 61, 65, 70 , 72, 73, 78, 82, 98 ,},
{ 112, 121, 112, 134, 123, 100, 98, 111,},
{ 136, 136, 136, 134, 147, 150, 154, 134,},
};
My method should return true if val is in the array and looks like this:
public boolean findValTest(int [][] m, int val){...}
It is possible iff. the matrix m is a square matrix of size n x n. Core idea is inspired by oleg.cherednik's answer. As soon as we find a row in m, such that m[row][0] >= val, we know that val must be in either row row or row - 1(since the same comparison on row - 1 was false). Thus, we have to find our candidate rows (O(n)) and then analyze only those two rows (also O(n)). If m is not square, but rectangular, the algorithm has a complexity of O(n + k), where n is the number of rows and k is the number of colums in m. This leads to the following algorithm.
public class Test {
public static boolean contains(final int[][]m, final int value) {
int candidateRow = m.length;
for (int row = 1; row < m.length; ++row) {
if (m[row][0] == value) {
return true;
}
if (m[row][0] > value) {
candidateRow = row;
break;
}
}
for (int val : m[candidateRow - 1]) {
if (val == value) {
return true;
}
}
if (candidateRow < m.length) {
for (int val : m[candidateRow]) {
if (val == value) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
int [][] testArray = new int [][]{
{ 0, 2, 1, 2, 0, 5, 5, 5 },
{ 21, 21, 7, 7, 7, 21, 21, 21 },
{ 21, 21, 21, 21, 21, 21, 21, 21 },
{ 21, 21, 23, 42, 41, 23, 21, 21 },
{ 60, 56, 57, 58, 53, 52, 47, 51 },
{ 61, 65, 70, 72, 73, 78, 82, 98 },
{ 112, 121, 112, 134, 123, 100, 98, 111 },
{ 136, 136, 136, 134, 147, 150, 154, 134 }
};
for (int[] row : testArray) {
for (int val : row) {
System.out.print(contains(testArray, val) + " ");
}
System.out.println();
}
System.out.println();
System.out.println();
final int[] notInMatrix = { -1, 3, 4, 6, 8, 22, 30, 59, 71, 113, 135 };
for (int val : notInMatrix) {
System.out.print(contains(testArray, val) + " ");
}
System.out.println();
}
}
We can improve the acutal runtime by determining the candidate lines through a binary search algorithm so that candidate lines are found in O(log(n)) instead of O(n). The asymptotical runtime will still be O(n) for square matrices and O(log(n) + k) for non-square n x k matrices. The idea for this was taken from Saeed Bolhasani's answer.
private static int findCandidateRow(final int[][] m, final int value) {
int lower = 0;
int upper = m.length;
int middle = (upper + 1) / 2;
while (middle != m.length
&& middle != 1
&& (m[middle][0] < value || m[middle - 1][0] > value)) {
if (m[middle][0] < value) {
lower = middle;
} else {
upper = middle;
}
middle = lower + (upper - lower + 1) / 2;
}
return middle;
}
your solution is here. i made a function that do binary search for first column. if the val find in the first column the function return true, else last period of 'l' and 'r' are benefit for us. 'r' and 'l' are always equal of have only one distance(r=l or abs(r-l)=1 ). lower bound of 'r' and 'l' are expected row that the val maybe exist in it. so we should search this row.
O(n) for binary search is Log(n) and for row search is n. so the final O(n) will be n.code is here:
static boolean binarySearch(int arr[][], int l, int r, int x)
{
if (r>=l)
{
int mid = l + (r - l)/2;
// If the element is present at the
// middle itself
if (arr[mid][0] == x)
return true;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid][0] > x)
return binarySearch(arr, l, mid-1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present
// in array
int row = Math.min(l,r);
for(int i=0; i<arr[0].length ;i++)
if(arr[row][i]==x)
return true;
return false;
}
Smth. like that. In case of Every number at row i is equals or smaller then every number on row i+1, than you can check only first element in each row to define a row, where required value could be. Element in unsorted row can be found only with full scan.
This algorithm have to scan 2 full rows only, which is O(n) where n - number of rows.
public static boolean findValTest(int[][] m, int val) {
for (int row = 0; row < m.length; row++) {
if (m[row][0] <= val && row != m.length - 1)
continue;
int r = row;
while (r >= row - 1 && r >= 0) {
for (int col = 0; col < m[r].length; col++)
if (m[r][col] == val)
return true;
r--;
}
return false;
}
return false;
}
Test cases:
System.out.println(findValTest(arr3, -1)); // false
System.out.println(findValTest(arr3, 5)); // true
System.out.println(findValTest(arr3, 7)); // true
System.out.println(findValTest(arr3, 55)); // false
System.out.println(findValTest(arr3, 47)); // true
System.out.println(findValTest(arr3, 147)); // true
System.out.println(findValTest(arr3, 200)); // false
System.out.println(findValTest(new int[][] { { 3, 4, 5 } }, 4)); // true

Iterate through array, sum and put results in new array

I have an arrayList filled with integers and I need to iterate through this arrayList, add the numbers up until a threshold is reached, then put the resulting sum into a second arrayList slot, and move back to where I left off in the original arrayList, keep iterating and summing until the threshold is reached and then put that in the second slot, and so on until all 40 original items have been summed and put into a smaller arrayList.
I've thought of using two nested loops but I can't get the two loops to work together.
I'm very new to Java and don't know how to do this. Any suggestions will be helpful.
This is what I have so far:
int threshold = 12;
int sumNum = 0;
int j = 0;
int arr1[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
for (int i = 0; i < arr1.length; i++) {
while (sumNum <= threshold) {
sumNum += arr[j];
j++
}//end while
}//end for
You can actually do this with just one loop. You don't need to move back, just stay where you are and keep going on the sum.
public static ArrayList<Integer> sums(ArrayList<Integer> arr, int threshold){
ArrayList<Integer> sumArr = new ArrayList<Integer>();
int s = 0; //Sum thus far, for the current sum
for(int i : arr){
s += i; //Add this element to the current sum
if(s >= threshold){ //If the current sum has reached/exceeded the threshold
sumArr.add(s); //Add it to the sumArray, reset the sum to 0.
s = 0;
}
}
return sumArr;
}
You can change the input param from ArrayList to int[] or Integer[] without any trouble whatsoever. Hooray for for-each loops!
Code to use the above:
public static void main(String[] args){
ArrayList<Integer> i = new ArrayList<Integer>();
//create arraylist 1..20
for(int x = 1; x <= 20; x++){
i.add(x);
}
System.out.println(sums(i).toString());
}
package com.test;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
int threshold = 12;
int sumNum = 0;
int j = 0;
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
List myList = new ArrayList();
for (int i = 0 ; i < arr1.length ; i++) {
sumNum += i;
if (sumNum >= threshold) {
myList.add(sumNum);
sumNum = 0;
}
}
for (int a = 0 ; a < myList.size() ; a++) {
System.out.println(myList.get(a));
}
}
}
output
15
13
17
21
12
13
14
How about something like this:
/**
* Sequentially adds numbers found in the source array until the sum >= threshold.
* <p/>
* Stores each threshold sum in a separate array to be returned to the caller
* <p/>
* Note that if the last sequence of numbers to be summed does not meet the threshold,
* no threshold sum will be added to the result array
*
* #param numbersToSum The source number list
* #param threshold The threshold value that determines when to move on to
* the next sequence of numbers to sum
*
* #return An array of the calculated threshold sums
*/
public static Integer[] sumWithThreshold(int[] numbersToSum, int threshold)
{
List<Integer> thresholdSums = new ArrayList<Integer>();
if (numbersToSum != null)
{
int workingSum = 0;
for (int number: numbersToSum)
{
workingSum = workingSum + number;
if (workingSum >= threshold)
{
thresholdSums.add(workingSum);
workingSum = 0;
}
}
}
return thresholdSums.toArray(new Integer[thresholdSums.size()]);
}
public static void main(String[] args)
{
int[] testNumbers =
{
1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,
31,32,33,34,35,36,37,38,39,40};
int[] thresholds = {1, 42, 100, 200};
for (int threshold: thresholds)
{
System.out.println("Threshold sums for threshold = " + threshold + ":\n" + Arrays.toString(sumWithThreshold(testNumbers, threshold)));
}
}
That produces the following output:
Threshold sums for threshold = 1:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
Threshold sums for threshold = 42:
[45, 46, 45, 54, 63, 47, 51, 55, 59, 63, 67, 71, 75, 79]
Threshold sums for threshold = 100:
[105, 105, 115, 110, 126, 105, 114]
Threshold sums for threshold = 200:
[210, 225, 231]

Finding mode and frequency of mode without sorting in Java

I'm new to Java, and was given a question to solve as a weekend project. I ran into some troubles, and would like your help. Please understand I am a beginner. If I'm wrong somewhere, please explain it to me. I hope to be a good programmer too some day.
I did a through search, and found answers with things like "heatmaps" or "arraylists", something I probably won't be allowed to use since I haven't learned it yet.
Ok, so the question given to me was:
Find: 1) Mode, the most frequently occurring marks in the class. If 2 or more marks occur equally frequently, then the highest of these marks is the mode.
2) Mode Frequency: Frequency of mode.
It is assumed that the class has 10 students and marks are between 0 to 100.You are not allowed to sort the marks.
This is my code for finding the mode:
void mode()
{
int c[]=new int[10];
int arr[]=new int[10];
for (int i=0;i<10;i++)
{
for (int j=i+1;j<10;j++)
{
for (int k=0;k<10;k++)
{
if (marks[i]!=arr[k])
{
if (marks[i]==marks[j])
{
c[i]++;
break;
}
}
}
arr[i]=marks[i];
}
}
for (int k=0;k<10;k++)
{
System.out.println();
System.out.println(c[k]);
}
}
Where marks[] is the int array where I take the input, c[] is to count the number of times the number is occurring, and arr[] is an array to cross check if the number has previously occurred or not.
Let's assume the 10 numbers inputted are 99, 95, 97, 92, 80, 95, 73, 80, 95, 80. As you can see 95 and 80 occur three times.
So my c[] should have {0, 2, 0, 0, 2, 0, 0, 0, 0, 0}, but when I run it, it comes as {0, 2, 0, 0, 2, 1, 0, 1, 0, 0}, which means my program isn't cross checking with arr[].
I think I've made a mess using three for-loops. I can't seem to figure out how to solve it.
One solution would be to have an array of length 101 initialized to zero. This array would represent the number of times a specific mark had occurred. each time you encounter a specific mark you increment the count. Then to find the mode, you simple find the index with the highest count.
public class Loader
{
// We suppose that the parameter is not null
public static void mode_frequency(long collection[])
{
long frequencies[] = new long[collection.length];
for (int i = 0, l = collection.length; i < l; i++)
{
for (int j = i; j < l; j++)
{
if (collection[i] == collection[j])
{
++frequencies[i];
}
}
}
// With your example {99, 95, 97, 92, 80, 95, 73, 80, 95, 80}
// You should have somthing like {1, 3, 1, 1, 3, 2, 1, 2, 1, 1}
//
// As you can see, you just have to find the MAX frequency and then, print corresponding values from initial array
long frequency = 0;
for (int i = 0, l = frequencies.length; i < l; i++)
{
if (frequency < frequencies[i])
{
frequency = frequencies[i];
}
}
// Print each mode
for (int i = 0, l = collection.length; i < l; i++)
{
if (frequencies[i] == frequency)
{
System.out.println(collection[i]);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
mode_frequency(new long[]
{
99,
95,
97,
92,
80,
95,
73,
80,
95,
80
});
}
}
You may want to use an algorithm in which you use secondary arrays to accumulate the counts for individual marks, and then search through those secondary arrays for the mark with the highest frequency with largest value. Consider:
package com.example.mode;
public class Mode {
public static void main(String[] args) {
int[] marks = { 99, 95, 97, 92, 80, 95, 73, 80, 95, 80};
//One algorithm .. insert marks and add occurances, keeping in order
int[] unique = new int[marks.length];
int[] count = new int[marks.length];
int maxUnique = 0;
for (int i=0; i < marks.length ; i++) {
int loc = -1;
for (int j=0; j < maxUnique; j++) {
if (marks[i] == unique[j]) {
loc = j;
break;
}
}
if (loc == -1) {
loc = maxUnique;
unique[loc] = marks[i];
count[loc] = 0;
maxUnique++;
}
count[loc] = count[loc]+1;
}
int maxValue = unique[0];
int maxCount = count[0];
for (int j=1; j < maxUnique; j++) {
if (count[j] > maxCount || (count[j] == maxCount && maxValue < unique[j]) ) {
maxValue = unique[j];
maxCount = count[j];
}
}
System.out.println("Mode = " + maxValue + ", frequency = " + maxCount);
}
}

How to create a random integer array generator

I have created a method which takes generate random numbers with the condition that the next random number doesn't match with the previous one inside the array here's the code
// some code
int k=0;
//some code....
randomgenerator(k); // method call
public void randomgenerator(int j)
{
for(j=0; j<=99; j++){
if(j >= 1){
if (randomset.get(j) == randomset.get(j-1)){
randomset.add(0 + ( j , int)(Math.random() * ((99 - 0) + 1)));
}
else{
randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1)));
}
}
}
}
The error I get is java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
Because initially randomset is empty therefore its size is 0 and returns exception at index 1. The best way to add randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1))); if j < 1 (not >=1).
Correct code:
public void randomgenerator(int j)
{
for(j=0; j<=99; j++){
if(j >= 1){
if (randomset.get(j) == randomset.get(j-1)){
randomset.add(0 + ( j , int)(Math.random() * ((99 - 0) + 1)));
}
else{
randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1)));
}
}
else {
randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1)));
}
}
}
Use
for(j=0; j<randomset.size(); j++){
Don't use the same variable as your input parameter and your loop variable.
public void randomgenerator(int length)
{
for (int j = 0; j < length; j ++) ...
I'm not sure I follow the rest of the code, but that's a start.
You can't reference an element of ArrayList whose index is not in bounds [0, size() - 1]. Creating ArrayList via ArrayList() creates a list of size 0. To add elements to this array you must call one of the methods that adds an element, e.g. add(). Your first call is to get(), but the list has size 0, so even get(0) will cause an IndexOutOfBoundsException.
What to do depends on the expected contents of the list. In your case, I would recommend writing a helper function that generates a random number in range excluding specified number. You could use that function in a simple loop to generate the whole list, passing previous element to mentioned helper function.
Example:
public static int randomInRange(int a, int b) {
return (int)(Math.random() * (b - a + 1));
}
public static int randomInRangeExcluding(int a, int b, int excluding) {
int result = (int)(Math.random() * (b - a));
if (result == excluding) {
result++;
}
return result;
}
public static List<Integer> generateRandomList(int size) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int j = 0; j <= size; j++) {
if (j > 0) {
result.add(randomInRangeExcluding(0, size - 1, result.get(j - 1)));
} else {
result.add(randomInRange(0, size - 1));
}
}
return result;
}
and get the value using:
generateRandomList(100);
Calling this results in a list of random integers having no two consecutive elements equal:
[27, 34, 53, 92, 56, 93, 21, 22, 45, 95, 48, 25, 18, 26, 54, 1, 82, 26, 5, 62, 84, 23, 8, 84, 25, 0, 36, 37, 54, 95, 4, 26, 65, 53, 81, 16, 47, 56, 73, 46, 60, 50, 37, 89, 61, 84, 23, 79, 47, 87, 68, 49, 15, 17, 55, 71, 17, 55, 71, 51, 67, 33, 80, 47, 81, 24, 10, 41, 76, 60, 12, 17, 96, 43, 57, 55, 41, 56, 21, 85, 98, 40, 9, 39, 53, 28, 93, 70, 89, 80, 40, 41, 30, 81, 33, 53, 73, 28, 38, 87, 29]
What is with you're function? You receive a parameter named j and then you reassigned it?
randomset.get(j) == randomset.get(j-1) <- at this line you have a java.lang.IndexOutOfBoundsException because you call for the value from position 1 but in you're list you have only a value on position 0; so an error is thrown
and, what is this ? ((99 - 0) + 1)) ,you could white 100, it is easy, and more readable
by the way, at this line you have an error, randomset.add(0 + ( j , (int)(Math.random() * ((99 - 0) + 1)));
You should write a cleaner code.
I've prepared a solution for you: a function which generates a List with random numbers and respects you condition: two consecutive numbers are not the same.
You must call this method generateRandomList with the number of elements you want to generate.
public static final Integer MAX_RANDOM_NUMBER = 100;
public static List<Integer> generateRandomList(int randomNumbers) {
return generateRandomList(randomNumbers, -1);
}
private static List<Integer> generateRandomList(final int randomNumbers, final int previousNumber) {
if (randomNumbers == 1) {
return new ArrayList<Integer>() {
{
add(getNextNumber(previousNumber));
}
};
} else {
return new ArrayList<Integer>() {
{
int value = getNextNumber(previousNumber);
add(value);
addAll(generateRandomList(randomNumbers - 1, value));
}
};
}
}
private static int getNextNumber(int previousNumber) {
boolean generateNewValue = true;
int currentValue = 0;
while (generateNewValue) {
currentValue = (int) (Math.random() * MAX_RANDOM_NUMBER);
generateNewValue = currentValue == previousNumber;
}
return currentValue;
}

Categories