Sum of digits in random generated arrays - java

I know this may stand for a silly question but I have got a lot of problems with this.
I will first explain how it should work :
1)Generate random Array with size in range <4,7>
2)Fill it with random elements in range <100, 999>
3)Print the index of three numbers with biggest digit sum
So the question is-how? I know I should implement this:
SumOfDigits += ElementFromArray % 10;
ElementFromArray /= 10;
But i have got no idea where. I tried to add this as a if (i>0) loop inside for loop-but its not working.
Also how at the end im going to print the proper elements? Should I use Arrays.sort(tab) and then System.out.println(tab[tab.length - 1]) (and so on with -2, -3 for 3 last elements)?
import java.util.Arrays;
import java.util.Random;
public class Ex1 {
public static void main(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int tab[] = new int[size];
for (int i = 0; i < tab.length; i++) {
int elements = rand.nextInt(900) + 100;
tab[i] = elements;
}
System.out.println(Arrays.toString(tab));
}
}

If we aim for a solution using only arrays I would use a 2d array to hold the sum of digits and the index of the corresponding number in the tab array
So first create the array based on the size of the original array
int[][] sums = new int[size][2];
then in the for loop, calculate the sum of the random number and store it and the index
sums[i][0] = elements / 100 + (elements / 10) % 10 + elements % 10;
sums[i][1] = i;
Then sort the sums array using a custom comparator
Arrays.sort(sums, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
And finally print the index and number of the numbers of the top 3
for (int i = 0; i < 3; i++) {
System.out.printf("%d: %d\n", sums[i][1], tab[sums[i][1]]);
}

Just use while loop: here is a quick and dirty solution:
private static void main10(String[] args) {
Random rand = new Random();
int size = rand.nextInt(4) + 4;
int[] tab = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = rand.nextInt(900) + 100;
tab[i] = element;
}
System.out.println(Arrays.toString(tab));
// calculate digits:
int[] digitsums = new int[size];
for (int i = 0; i < tab.length; i++) {
int element = tab[i];
int sumOfDigits = 0;
while (element > 0) {
sumOfDigits += element % 10;
element /= 10;
}
digitsums[i] = sumOfDigits;
}
System.out.println(Arrays.toString(digitsums));
int[] copyOfdigitsums = Arrays.copyOf(digitsums, digitsums.length);
for (int i = 1; i <= 3; i++) {
int j = getIndexOfLargest(copyOfdigitsums);
System.out.println("index of " + i + "largest is " + j + ", with a digitsum of " + copyOfdigitsums[j]);
copyOfdigitsums[j] = 0;
}
}
static int getIndexOfLargest(int[] digitsums) {
int largest = 0;
int index = 0;
for (int i = 0; i < digitsums.length; i++) {
int d = digitsums[i];
if (largest < d) {
largest = d;
index = i;
}
}
return index;
}

Related

Fisher yates Shuffle

static void shuffle(int[] array) {
int n = array.length;
for (int i = 0; i < array.length; i++) {
// Get a random index of the array past i.
int random = i + (int) (Math.random() * (n - i));
// Swap the random element with the present element.
int randomElement = array[random];
array[random] = array[i];
array[i] = randomElement;
}
}
public static void main(String[] args) {
int[] values = { 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14,15,16,17,18,19,20};
// Shuffle integer array.
shuffle(values);
// Display elements in array.
for (int value :values) {
System.out.print(" " +value);
//System.out.println(val);
}
}
I want to change the value array by name, for example deni, amir, cintia and others
Help , im newbie
I have succeeded in completing it :))
static void shuffle(String[] array) {
int n = array.length;
for (int i = 0; i < array.length; i++) {
// Get a random index of the array past i.
int random = i + (int) (Math.random() * (n - i));
// Swap the random element with the present element.
String randomElement = array[random];
array[random] = array[i];
array[i] = randomElement;
}
}

Random Char in 2D arrays

Hi i am new at java coding and am trying to create random numbers(which i have done) and i am trying to assign this random numbers as coordinates into the 2D array and print 'A' at the coordinates. Any help is appreciated.
package training;
import java.util.Random;
public class Training {
public static void main(String[] args) {
char[][] values = new char[10][10];
int foodX[] = new int[15];
for (int i = 1; i < foodX.length + 1; i++) {
int minFood = 0;
int maxFood = 10;
int randNum1 = minFood + (int) (Math.random() * (maxFood - minFood) + 1);
int minFoodY = 0;
int maxFoodY = 10;
int randNum2 = minFoodY + (int) (Math.random() * (maxFoodY - minFoodY) + 1);
for (int j = 1; j < foodX.length + 1; j++) {
values[randNum1][randNum2] = 'A';
}
}
// Assign three elements within it.
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
char[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}
Arrays in Java are zero-indexed. What this means is that if you declare an array myArray as follows:
final int[] myArray = new int[10];
then you are creating a 10-element array which contains values in myArray[0], myArray[1], ..., myArray[9]. This also holds true for two-dimensional arrays, such as the values array in your code. However, you have defined randNum1 and randNum2 to return values in the range 1 to 10. When either of those values is set to 10, then values[randNum1][randNum2] will throw an ArrayIndexOutOfBoundsException, because you are trying to reference the array using indices that are out of its range.
In addition to this, you have created an array, foodX, which you do nothing with beyond determining its length. It's better in this case to declare an constant int value for this purpose. Finally, although you have imported the java.util.Random class, you are using Math.random() to generate random variables, which doesn't rely on this. You could alternatively use Random.nextDouble(), which would be useful if using a random number seed, but that's an aside.
Without following any additional considerations and to get your output simply to work as I believe is intended, I would therefore re-write your class in the following way:
package training;
public class Training {
public static void main(String[] args) {
char[][] values = new char[10][10];
int foodSize = 15
for (int i = 1; i <= foodSize; i++) {
int minFood = 0;
int maxFood = 10;
int randNum1 = minFood + (int) (Math.random() * (maxFood - minFood));
int minFoodY = 0;
int maxFoodY = 10;
int randNum2 = minFoodY + (int) (Math.random() * (maxFoodY - minFoodY));
values[randNum1][randNum2] = 'A';
// I've removed the for loop in the line above since it simply does the same thing 15 times and is inefficient
}
// Assign three elements within it.
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
char[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}

How to display newly sorted integers?

I am doing a project in which the user enters a number, x ,it will then generate x amount of random numbers and add them to an arraylist. In one text field, it will display however many random integers are in the array, I then have to make it so in another textfield, it sorts those numbers through a selection sorting. I'm pretty sure I have the code for it right, I'm just not sure how to get the sorted numbers to display on the text field #2. Heres what I have:
ArrayList <Integer> Numbers = new ArrayList <Integer>();
....
String input;
int int1,int2 = 0, min = -1000, max = 1000,j, maximum;
input = Input.getText();
int1 = Integer.parseInt(input);
Random number = new Random();
while(int2 < int1){
for (int i = 0; i < int1; i++){
int randomInt = number.nextInt(max - min + 1) + min;
Numbers.add(randomInt);
int1--;
}
}
if(Selection.isSelected() && Ascending.isSelected()){
for (int i = 0; i<Numbers.size()-1; i++){
maximum = i;
for(j = i+1; j<=Numbers.size()-1;j++){
if(j < i){
int temp = i;
i = j;
j = temp;
}
}
}
}
Output1.setText("Unsorted Numbers " + Numbers);
Output2.setText("Sorted Numbers " + //what here? );
Numbers.clear();
Thanks for any help you might be able to offer.
what about this ?
public static void main(String[] args) {
//min and max value
int min = -1000;
int max = 1000;
//collection to store numbers
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random random = new Random();
//receive input
Scanner myScanner = new Scanner(System.in);
int numberFromUser = Integer.parseInt(myScanner.nextLine());
for (int i = 0; i < numberFromUser; i++) {
numbers.add(random.nextInt(max - min + 1) + min);
}
System.out.println("Unsorted :" + numbers);
// sort the numbers
Collections.sort(numbers);
System.out.println("Sorted :" + numbers);
numbers.clear();
}
You should prepare a string:
String sortedNumbersOutput = "";
for (int i = 0; i < sortedNumbers.size(); i++) {
sortedNumbersOutput += sortedNumbers.get(i) + (i != sortedNumbers.size() - 1 ? "," : "");
}
Output2.setText("Sorted Numbers " + sortedNumbersOutput );
On a separate note, I don't believe you are sorting your list...
You are comparing on the indices and not the values at those indices.
Maybe you want to try:
boolean changes = true;
int temp;
while (changes) {
changes = false;
for (int i = 0; i < Numbers.size()-1; i++){
if (Numbers.get(i) > Numbers.get(i+1)) {
temp = Numbers.get(i);
Numbers.set(i, Numbers.get(i+1));
Numbers.set(i+1, temp);
changes = true;
}
}
}
which is called a bubble sort

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