Array Parameter proplem - java

I'm stuck..... i have been trying to use Arrays in methods to count the number of numbers divisible by 10 from the range 1-100.
here's my code:
import java.util.Scanner;
import java.util.Random;
public class Journal5a {
// METHOD
public int[] creatArray (int size)
{
int[] array = new int[size];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt(100);
return array;
}
public int[] DivByTen()
{
int x = 0;
int y[] = this.creatArray(1);
for (int i = 0; i < y.length; i++)
if (y[i] % 10 == 0)
{
x++;
}
return x;
}
public int[] printArray ()
{
int[] myArray = this.creatArray(1);
for (int i = 0; i<myArray.length; i++)
System.out.println(myArray[i]);
return myArray;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Journal5a j5a = new Journal5a();
j5a.DivByTen();
}
So my output would be :
there is 10 numbers divisible by 10
Another problem is the x used in the method DivByTen isn't being returned.

Your createArray() method fills the array with random numbers from 0-99, so it is not clear how much numbers are dividable by 10.
for(int i = 0; i < size; i++) {
array[i] = i;
}
will create an array with values from 0 to size - 1.
The second problem is that your return type is int[] instead of int

First, create and fill the array. For the range 1 to 100 you would need to pass in 100 and either start with i at 1 (or add 1 to i when you initialize the array);
private static int[] creatArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
Next, count the multiples of some multiple. Something like,
private static int countMultiples(int[] arr, int multiple) {
int count = 0;
for (int val : arr) {
if (val != 0 && val % multiple == 0) {
count++;
}
}
return count;
}
Finally, call the above methods and output the result
public static void main(String[] args) {
final int multiple = 10;
int count = countMultiples(creatArray(100), multiple);
System.out.printf("There are %d numbers divisible by %d.", count, multiple);
}
Output is
There are 10 numbers divisible by 10.

Related

Create Random Int Array giving a lenght and a range of values in JAVA

I am trying to program a Java Code in which, given the lenght of an int array and a min and max values it returns an random array values.
I am trying to program it in the most simple way, but I am still not getting how the programming process works.
What I have tried is the following:
import java.util.Random;
public class RandomIntArray {
public static void main(String[] args){
System.out.println(createRandom(10));
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 99;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt();
while (array[i] > min) ;
while (array[i] < max) ;
}
return array;
}
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 10;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt(max-min+1) + min;
System.out.print(array[i] +" ");
}
return array;
}
public static void main(String[] args){
createRandom(5);
}
Try using IntStream to achieve what you want
public static void main(String[] args) {
int[] arr = createRandom(10);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static int[] createRandom(int n) {
Random r = new Random();
int min = 5;
int max = 99;
return IntStream
.generate(() -> r.nextInt(max - min) + min)
.limit(n)
.toArray();
}
The first thing we must adjust is the random number generation. It appears you specify a min and max, so a number must be generated in with these bounds. We can use the Random.nextInt(int bound) method to set a range equal to max - min. However, this range will start from 0, so we must add your min value to make the bound complete. Using this process will eliminate the need for the existing while loops. See this question for more on this.
Now, every value in the array will be generated as
array[i] = rd.nextInt(max - min) + min
When trying to print array elements, a System.out.println() statement with the variable name of the array will print a memory address of the array. This will NOT print the entire array of values.
We must instead iterate over the elements to print them. It would be best to use a for loop to do this, but your program could generate an array of any size. So, we should use a for-each loop instead as follows:
for (int num : createRandom(10)) {
System.out.println(num);
}
This for-each is saying "for each int in the array returned by createRandom(10), refer to is as variable num and print it."
This is the final code:
import java.util.Random;
public class RandomIntArray {
public static void main(String[] args){
for (int num : createRandom(10)) {
System.out.println(num);
}
}
public static int[] createRandom(int n) {
Random rd = new Random();
int[] array = new int[n];
int min = 5;
int max = 99;
for (int i = 0; i < array.length; i++) {
array[i] = rd.nextInt(max - min) + min;
System.out.println(array[i]);
}
return array;
}
}

Java: Given a number, get the highest sequential occurrences in an Array

I am new to Java Programming (or programming infact).
I have an array which contains either 4 or 6 only. Given a number, either 4 or 6, find the highest sequential occurrence of the given number.
I need highest sequential occurrence count
Example: arr[{4,4,6,6,4,4,4,4,4,6}]
If the above array is given, and next input number is 4, the output should be 5. Because the number 4 has occurred sequentially 5 times.
public static void main(String[] args) throws IOException {
String arrayTK = br.readLine(); // Input is 4466444446
int[] inpArray = new int[10];
for (int i = 0; i < 10; i++) {
inpArray[i] = arrayTK.charAt(i) - '0';
}
int maxSequenceTimes = 0;
for (int j = 0; j < 10; j++) {
// Logic
}}
Any help would be greatly appreciated.
Edit
We will separate and count all sequences and then search in each sequence to know which sequence contain the biggest length.
int[] arr = {4,4,6,6,4,4,4,4,4,6};
boolean newSeq = false;
int diffrentSeq = 0;
int currentNumber;
//Get sequence numbers
for (int i = 0; i < arr.length; i++) {
currentNumber = arr[i];
if (i >= 1 && currentNumber != arr[i - 1])
newSeq = true;
else if (i == 0)
newSeq = true;
//It's new sequence!!
if (newSeq) {
diffrentSeq++;
newSeq = false;
}
}
System.out.println(diffrentSeq);
int[] maxSequencSize = new int[diffrentSeq];
int lastIndex = 0;
for (int i = 0; i < maxSequencSize.length; i++) {
int currentNum = arr[lastIndex];
for (int j = lastIndex; j < arr.length; j++) {
if (arr[j] == currentNum) {
maxSequencSize[i]++;
lastIndex = j + 1;
} else break;
}
}
System.out.println(max(maxSequencSize));
You need to get max value which act the max sequence length:
private static int max(int[] array){
int maxVal = 0;
for (int anArray : array) {
if (anArray > maxVal)
maxVal = anArray;
}
return maxVal;
}
String arrayTK = br.readLine(); // Input is 4466444446
Because your first input is a string, you don't need to convert it to an int array and if you are using you can use:
String arrayTK = "4466444446";
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream().max(Comparator.comparingInt(String::length)).get().length();
System.out.println(result);
Explanation :
arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2") put a separator between each two different numbers the result should be 44;66;44444;6
.split(";") split with this separator (i used ; in this case) the result is ["44", "66", "44444", "6"]
stream().max(Comparator.comparingInt(String::length)).get() get the max input
.length() to return the length of the result
Ideone demo
Edit
How I modify the same, to get count to any specific number. I mean, max sequential occurrence of number 4
In this case you can just add a filter .filter(t -> t.matches(number + "+")) which mean get only the numbers which match 4+ where 4 can be any number :
...
int number = 6;
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream()
.filter(t -> t.matches(number + "+"))
.max(Comparator.comparingInt(String::length)).get().length();
You need something like this:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner br =new Scanner(System.in);
String str = br.next();
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i)-'0';
//System.out.println(arr[i]);
}
int j=0;
int count=1,max=0;
for(int i=0;i<str.length();i++)
{
if(i==0){
j=arr[i];
}
else
{
if(arr[i]==j)
{
count++;
//System.out.println(" "+count);
}
else
{
if(max<count){
max=count;
}
count=1;
j=arr[i];
}
}
}
if(max<count){
max=count;
}
System.out.println(max);
}
}
That should do the work. Every time you find the matching value you start counting and when the streak is over you compare the length with the maximum length you have found so far.
public int logic(int[] inpArray, int num) {
int count = 0, max = 0
for(int i = 0; i < 10; ++i){
if(inpArray[i] == num) {
count++
else{
if(count > max)
max = count;
count = 0;
}
}
if (count > max)
max = count;
return max;
}

Count how many integers were displayed in an array

I got an 100 random elements array, each element is in range of 0-10, and i need to count each integer how many times it was typed (e.g. 1,2,2,3,8,8,4...)
OUTPUT:
1 - 1
2 - 2
3 - 1
8 - 2
4 - 1
My code so far is:
import java.util.Random;
public class Asses1 {
public static void main(String[] args) {
getNumbers();
}
private static int randInt() {
int max = 10;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
System.out.println(randInt());
}
System.out.println(number+" random numbers were displayed");
return array;
}
}
Add this method, which will do the counting:
public static void count(int[] x) {
int[] c=new int[11];
for(int i=0; i<x.length; i++)
c[x[i]]++;
for(int i=0; i<c.length; i++)
System.out.println(i+" - "+c[i]);
}
and change the main into this so that you call the previous method:
public static void main(String[] args) {
count(getNumbers());
}
Also, change the for loop in getNumbers into this in order to fill array with the generated numbers, not just printing them:
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
System.out.println(array[i]);
}
Here is how it can be done in java 8
// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));
Output:
[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]
NB: Your method getNumbers is not correct you should fix it as next:
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
}
System.out.println(number+" random numbers were displayed");
return array;
}
int[] array2 = new int[11];
for (int i = 0; i < array.length; i++){
array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));
What I have done is:
Create an helping array array2 for storing number of occurences of each number.
When generating numbers increment number of occurences in helping array.
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int temp;
for (int i = 0; i < array.length; i++) {
temp=randInt();
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
}else{
map.put(temp, 1);
}
}

Finding multiple modes in an array of integers with 1000 elements

So I need a way to find the mode(s) in an array of 1000 elements, with each element generated randomly using math.Random() from 0-300.
int[] nums = new int[1000];
for(int counter = 0; counter < nums.length; counter++)
nums[counter] = (int)(Math.random()*300);
int maxKey = 0;
int maxCounts = 0;
sortData(array);
int[] counts = new int[301];
for (int i = 0; i < array.length; i++)
{
counts[array[i]]++;
if (maxCounts < counts[array[i]])
{
maxCounts = counts[array[i]];
maxKey = array[i];
}
}
This is my current method, and it gives me the most occurring number, but if it turns out that something else occurred the same amount of times, it only outputs one number and ignore the rest.
WE ARE NOT ALLOWED TO USE ARRAYLIST or HASHMAP (teacher forbade it)
Please help me on how I can modify this code to generate an output of array that contains all the modes in the random array.
Thank you guys!
EDIT:
Thanks to you guys, I got it:
private static String calcMode(int[] array)
{
int[] counts = new int[array.length];
for (int i = 0; i < array.length; i++) {
counts[array[i]]++;
}
int max = counts[0];
for (int counter = 1; counter < counts.length; counter++) {
if (counts[counter] > max) {
max = counts[counter];
}
}
int[] modes = new int[array.length];
int j = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] == max)
modes[j++] = array[i];
}
toString(modes);
return "";
}
public static void toString(int[] array)
{
System.out.print("{");
for(int element: array)
{
if(element > 0)
System.out.print(element + " ");
}
System.out.print("}");
}
Look at this, not full tested. But I think it implements what #ajb said:
private static int[] computeModes(int[] array)
{
int[] counts = new int[array.length];
for (int i = 0; i < array.length; i++) {
counts[array[i]]++;
}
int max = counts[0];
for (int counter = 1; counter < counts.length; counter++) {
if (counts[counter] > max) {
max = counts[counter];
}
}
int[] modes = new int[array.length];
int j = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] == max)
modes[j++] = array[i];
}
return modes;
}
This will return an array int[] with the modes. It will contain a lot of 0s, because the result array (modes[]) has to be initialized with the same length of the array passed. Since it is possible that every element appears just one time.
When calling it at the main method:
public static void main(String args[])
{
int[] nums = new int[300];
for (int counter = 0; counter < nums.length; counter++)
nums[counter] = (int) (Math.random() * 300);
int[] modes = computeModes(nums);
for (int i : modes)
if (i != 0) // Discard 0's
System.out.println(i);
}
Your first approach is promising, you can expand it as follows:
for (int i = 0; i < array.length; i++)
{
counts[array[i]]++;
if (maxCounts < counts[array[i]])
{
maxCounts = counts[array[i]];
maxKey = array[i];
}
}
// Now counts holds the number of occurrences of any number x in counts[x]
// We want to find all modes: all x such that counts[x] == maxCounts
// First, we have to determine how many modes there are
int nModes = 0;
for (int i = 0; i < counts.length; i++)
{
// increase nModes if counts[i] == maxCounts
}
// Now we can create an array that has an entry for every mode:
int[] result = new int[nModes];
// And then fill it with all modes, e.g:
int modeCounter = 0;
for (int i = 0; i < counts.length; i++)
{
// if this is a mode, set result[modeCounter] = i and increase modeCounter
}
return result;
THIS USES AN ARRAYLIST but I thought I should answer this question anyways so that maybe you can use my thought process and remove the ArrayList usage yourself. That, and this could help another viewer.
Here's something that I came up with. I don't really have an explanation for it, but I might as well share my progress:
Method to take in an int array, and return that array with no duplicates ints:
public static int[] noDups(int[] myArray)
{
// create an Integer list for adding the unique numbers to
List<Integer> list = new ArrayList<Integer>();
list.add(myArray[0]); // first number in array will always be first
// number in list (loop starts at second number)
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is different
if (myArray[i] != myArray[i - 1])
list.add(myArray[i]); // add it to the list
}
int[] returnArr = new int[list.size()]; // create the final return array
int count = 0;
for (int x : list) // for every Integer in the list of unique numbers
{
returnArr[count] = list.get(count); // add the list value to the array
count++; // move to the next element in the list and array
}
return returnArr; // return the ordered, unique array
}
Method to find the mode:
public static String findMode(int[] intSet)
{
Arrays.sort(intSet); // needs to be sorted
int[] noDupSet = noDups(intSet);
int[] modePositions = new int[noDupSet.length];
String modes = "modes: no modes."; boolean isMode = false;
int pos = 0;
for (int i = 0; i < intSet.length-1; i++)
{
if (intSet[i] != intSet[i + 1]) {
modePositions[pos]++;
pos++;
}
else {
modePositions[pos]++;
}
}
modePositions[pos]++;
for (int modeNum = 0; modeNum < modePositions.length; modeNum++)
{
if (modePositions[modeNum] > 1 && modePositions[modeNum] != intSet.length)
isMode = true;
}
List<Integer> MODES = new ArrayList<Integer>();
int maxModePos = 0;
if (isMode) {
for (int i = 0; i< modePositions.length;i++)
{
if (modePositions[maxModePos] < modePositions[i]) {
maxModePos = i;
}
}
MODES.add(maxModePos);
for (int i = 0; i < modePositions.length;i++)
{
if (modePositions[i] == modePositions[maxModePos] && i != maxModePos)
MODES.add(i);
}
// THIS LIMITS THERE TO BE ONLY TWO MODES
// TAKE THIS IF STATEMENT OUT IF YOU WANT MORE
if (MODES.size() > 2) {
modes = "modes: no modes.";
}
else {
modes = "mode(s): ";
for (int m : MODES)
{
modes += noDupSet[m] + ", ";
}
}
}
return modes.substring(0,modes.length() - 2);
}
Testing the methods:
public static void main(String args[])
{
int[] set = {4, 4, 5, 4, 3, 3, 3};
int[] set2 = {4, 4, 5, 4, 3, 3};
System.out.println(findMode(set)); // mode(s): 3, 4
System.out.println(findMode(set2)); // mode(s): 4
}
There is a logic error in the last part of constructing the modes array. The original code reads modes[j++] = array[i];. Instead, it should be modes[j++] = i. In other words, we need to add that number to the modes whose occurrence count is equal to the maximum occurrence count

how to get the most common character in an array?

Suppose I have an integer array like this:
{5,3,5,4,2}
and I have a method which returns the most common character
public int highestnumber(String[] num) {
int current_number = Integer.parseInt(num[0]);
int counter = 0;
for (int i = 1; i < num.length; ++i) {
if (current_number == Integer.parseInt(num[i])) {
++counter;
} else if (counter == 0) {
current_number = Integer.parseInt(num[i]);
++counter;
} else {
--counter;
}
}
return current_number;
}
but if I have multiple common character then i need to get the number which is closest to one(1), like if i have an array like this:
{5,5,4,4,2};
then the method should return 4, what should I do for this?
As per what I understand your question,
What you have to done is,
1. Create ArrayList from your int[]
2. Use HashMap for find duplicates, which one is unique
3. Sort it as Ascending order,
4. First element is what you want..
EDIT: Answer for your question
int[] arr = {5, 4, 5, 4, 2};
ArrayList<Integer> resultArray = new ArrayList<Integer>();
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++)
{
if (set.contains(arr[i]))
{
System.out.println("Duplicate value found at index: " + i);
System.out.println("Duplicate value: " + arr[i]);
resultArray.add(arr[i]);
}
else
{
set.add(arr[i]);
}
}
Collections.sort(resultArray);
for (int i = 0; i < resultArray.size(); i++)
{
Log.e("Duplicate Values:", resultArray.get(i) + "");
}
Your need is,
int values = resultArray.get(0);
Sort the array then count runs of values.
Fast way.
Create a counter int array one element for each number. Go through the array once and increment corresponding counter array for each number. Set highest number to first counter element then go through and change highest number to current element only if it is bigger than highest number, return highest number.
public int highestNumber(String[] num){
int[] count = new int[10];
int highest_number = 0;
int highest_value = 0;
for(int i = 0; i < num.length; i++)
count[Integer.parseInt(num[i])]++;;
for(int i = 0; i < count.length; i++)
if(count[i] > highest_value){
highest_number = i;
highest_value = count[i];
}
return highest_number;
}
10x slower but without other array.
Create three ints one for number and two for counting. Go through the array once for each int and increment current counting each time it shows up, if bigger that highest count, set to highest count and set highest number to current count. Return highest number.
public int highestNumber(String[] num){
int highest_number = 0;
int highest_value = 0;
int current_value = 0;
for(int i = 0; i < 10; i++){
for(int j = 0; j < num.length; j++)
if(i == Integer.parseInt(num[j]))
current_value++;
if(current_value > highest_value){
highest_value = current_value;
highest_number = i;
}
current_value = 0;
}
return highest_number;
}
The first is obviously much faster but if for whatever reason you don't want another array the second one works too.
You can also try this:
import java.util.TreeMap;
public class SmallestFrequentNumberFinder {
public static int[] stringToIntegerArray(String[] stringArray) {
int[] integerArray = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
integerArray[i] = Integer.parseInt(stringArray[i]);
}
return integerArray;
}
public static int getSmallestFrequentNumber(int[] numbers) {
int max = -1;
Integer smallestFrequentNumber = null;
TreeMap<Integer, Integer> frequencyMaper = new TreeMap<Integer, Integer>();
for (int number : numbers) {
Integer frequency = frequencyMaper.get(number);
frequencyMaper.put(number, (frequency == null) ? 1 : frequency + 1);
}
for (int number : frequencyMaper.keySet()) {
Integer frequency = frequencyMaper.get(number);
if (frequency != null && frequency > max) {
max = frequency;
smallestFrequentNumber = number;
}
}
return smallestFrequentNumber;
}
public static void main(String args[]) {
String[] numbersAsString = {"5", "5", "4", "2", "4", "4", "2", "2"};
final int[] integerArray = stringToIntegerArray(numbersAsString);
System.out.println(getSmallestFrequentNumber(integerArray));
}
}

Categories

Resources