i just created an array have 100 elements, so now i want get 10 elements print first, secondly i want continuing 10 elements print out, and 10 elements third keep going. My code is below:
int[] array = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,..., 100 };
int count = 0;
for (int i = 0; i < array.length; i++) {
count++;
if (count == 10) {
System.out.println(array[i]);
count = 0;
}
}
Your logic is correct, only issue is with the printing of array values.
int[] array = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,....,100};
int count = 0;
for (int i = 0; i < array.length; i++) {
count++;
System.out.print(array[i]+" ");
if (count == 10) {
System.out.println();
count = 0;
}
}
This can be done fairly easily by iterating through the array with a double for-loop.
One loop will iterate through the modulo index and the other will print the 10 elements with that modulo value.
int[] array = {1,2,3,4,5,6,7,8,9,10,...,100};
for (int offset = 0; offset < array.length/10; offset++)
for (int i = 0 + offset; i < array.length; i+= array.length/10)
System.out.println(array[i]);
Related
I am trying to write a java method to find the mode in an unsorted integer array. This works fine when there is only one mode within the array. But it gives out a random number when there's no mode in the array.
And also I need to make sure that my method addresses multimodal arrays as well. But I find difficulty in editing the code to return an array of modes.
public static int mode(int[] marksArray){
int maxValue =0;int maxCount = 0;
for (int i = 0; i < marksArray.length; ++i) {
int count = 0;
for (int j = 0; j < marksArray.length; ++j) {
if (marksArray[j] == marksArray[i]) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = marksArray[i];
}
}
return maxValue;
}
If there's more than one mode in the array then your code returns the first, which is not unreasonable.
To return all modes you need to maintain a list.
static List<Integer> mode(int[] array)
{
List<Integer> mode = new ArrayList<>();
int maxCount = 2;
for(int i=0; i<array.length; i++)
{
int count = 1;
for(int j=i+1; j<array.length; j++)
if(array[i] == array[j]) count++;
if(count >= maxCount)
{
if(count > maxCount)
{
mode.clear();
maxCount = count;
}
mode.add(array[i]);
}
}
return mode;
}
Note that there's no need to start the inner loop at 0. You can initialize count to 1 and start at i+1. Actually this is important as it means that the count for subsequent instances of array[i] will be less than the initial count, so they won't get added to the list as equal modes.
I've edited the code to detect the case where every element of the array is distinct, in which case there's no mode.
In Java 8+, it can be done like this:
public static int[] modes(int[] marksArray) {
Entry<Long, List<Integer>> max = Arrays.stream(marksArray).boxed()
.collect(groupingBy(identity(), TreeMap::new, counting())).entrySet().stream()
.filter(e -> e.getValue() > 1)
.collect(groupingBy(Entry::getValue, TreeMap::new, mapping(Entry::getKey, toList())))
.lastEntry();
return (max == null ? new int[0] : max.getValue().stream().mapToInt(Integer::intValue).toArray());
}
Test
public static void main(String[] args) {
// Samples from https://www.mathsisfun.com/mode.html
// and https://www.purplemath.com/modules/meanmode.htm
test(); // []
test(1, 2, 4, 7); // []
test(6, 3, 9, 6, 6, 5, 9, 3); // [6]
test(1, 3, 3, 3, 4, 4, 6, 6, 6, 9); // [3, 6]
test(13, 18, 13, 14, 13, 16, 14, 21, 13); // [13]
test(8, 9, 10, 10, 10, 11, 11, 11, 12, 13); // [10, 11]
}
public static void test(int... marksArray) {
System.out.println(Arrays.toString(modes(marksArray)));
}
Output
[]
[]
[6]
[3, 6]
[13]
[10, 11]
Currently working on an algorithm that replaces every element with the next greatest element, but unlike some other questions here, this one is not concerned with replacing values with -1 if no such number exists, and it must be in ascending order.
Given this input: {1, 5, -3, 2, 8, 4, 7, 10, 3, 11, 2 }
Have to get this output: 1 5 5 5 8 8 8 10 10 11 11
This is what I have so far:
class Playground {
static void nextGreatest(int arr[]) {
int size = arr.length;
// Initialize the next greatest element
int max_from_right = arr[size - 1];
// Replace all other elements with the next greatest
for (int i = 1; i < size; i++)
{
// Store the current element (needed later for
// updating the next greatest element)
int temp = arr[i];
// Replace current element with the next greatest
arr[i] = max_from_right;
// Update the greatest element, if needed
if(max_from_right < temp) {
max_from_right = temp;
}
}
}
// prints the array
static void printArray(int arr[])
{
for (int i=0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static void main (String[] args) {
int arr[] = {1, 5, -3, 2, 8, 4, 7, 10, 3, 11, 2 };
nextGreatest (arr);
printArray (arr);
}
}
And I get the following right now:
1 2 5 5 5 8 8 8 10 10 11
Thoughts?
Thanks
(Not sure I understand your question exactly, but based on the clarification from the comments here is my answer...)
Seems you just need to change the initial max initialization to the first element rather than the last element.
int currentMax = arr[0];
for (int i = 1; i < size; i++) {
int temp = arr[i];
arr[i] = currentMax;
if(currentMax < temp) {
currentMax = temp;
}
}
The solution ends up as For each index i, what is the maximum element seen so far.
Consider the following:
int currMax = -1;
int[] input = {1, 5, -3, 2, 8, 4, 7, 10, 3, 11, 2};
for (int i = 0; i < input.length; i++){
if (input[i] > currMax){ // if we find a new max element
currMax = input[i];
}
else if (input[i] < currMax){ // if value is less then max we replace it
input[i] = currMax;
}
}
System.out.println(Arrays.toString(input));
> [1, 5, 5, 5, 8, 8, 8, 10, 10, 11, 11]
Based on this answer I've tried to do my roulette wheel selection in genetic algorithm.
private static final int NUMBER_OF_TOURISTS = 20;
private static int[] roulette(int population[]) {
int sumProb = 0;
for (int i = 0; i < population.length; i++) {
sumProb += population[i];
}
int[] rouletteIndex = new int[NUMBER_OF_TOURISTS];
Random r = new Random();
for (int i = 0; i < NUMBER_OF_TOURISTS; i++) {
int numberRand = r.nextInt(sumProb);
//-------------------------------------------------------
int j = 0;
while (numberRand > 0) {
numberRand = numberRand - population[j];
j++;
}
rouletteIndex[i] = j-1;
//-------------------------------------------------------
}
return rouletteIndex;
}
after this I get:
[6, 2, -1, 19, 13, 2, 14, 2, 6, 19, 7, 14, 18, 0, 1, 9, 13, 10, 7, 2]
"-1"? But how, when j should be always greater than 0.
Is this happen when numberRand = 0 and than while loop doesn't start even once? But how to fix this?
Random.nextInt(int bound) returns 0 (inclusive) to specified bound (exclusive).
So your loop:
while (numberRand > 0) {
numberRand = numberRand - population[j];
j++;
}
Will not run if nextInt(int bound) returns 0, resulting in j being 0 at: rouletteIndex[i] = j-1;
I'm trying to find the evens and odds of an array for practice.
Sample Data :
2 4 6 8 10 12 14
1 2 3 4 5 6 7 8 9
2 10 20 21 23 24 40 55 60 61
Sample Output :
Odds - []
Evens - [2, 4, 6, 8, 10, 12, 14]
Odds - [1, 3, 5, 7, 9]
Evens - [2, 4, 6, 8]
Odds - [21, 23, 55, 61]
Evens - [2, 10, 20, 24, 40, 60]
And here is my code so far:
import java.util.Scanner;
public class OddsAndEvens
{
private static int countEm(int[] array, boolean odd)
{
int count = 0;
int dum = 0;
for(int i=0; i< array.length; i++)
{
dum = array[i] / 2;
if(dum == 0 )
{
count++;
}
}
return count;
}
public static int[] getAllEvens(int[] array)
{
int numberEvens=0;
for(int i =0; i<array.length; i++)
{
if(array[i]%2 ==0)
{
numberEvens++;
}
}
int[] evens = new int[array.length - countEm(array,false)];
int count=0;
for(int i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
evens[count] = array[i];
count++;
}
}
return evens;
}
public static int[] getAllOdds(int[] array)
{
int numberEvens = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
numberEvens++;
}
}
return null;
}
}
But I been getting errors in my output. These errors are the fact I am getting zeros in my output .
I'm just starting out and I'm hoping anyone can help me.
Your main problem comes from your countEm method. It is also the reason for all the extra zeroes behind your array. By doing minimal changes can solve these problems and make your program work.
One of the major careless mistake is that you used / instead of % for checking evens and odds in your countEm method.
Your countEm method is incomplete
Using wrong operator to count even/odd
Your incomplete countEm method now only counts the number of even number no matter the Boolean value is true or false. I've helped you implemented the complete countEm:
private static int countEm(int[] array, boolean odd)
{
int numEven = 0;
int numOdd = 0;
for(int i=0; i< array.length; i++)
if(array[i] % 2 == 0 ) //You used / instead of % earlier!
numEven++;
else
numOdd++;
if(odd)
return numOdd;
else
return numEven;
}
Make the above changes, I am sure it will work. Of course, you haven't complete your method for getting getAllOdds yet. Above changes will make your getAllEvens work properly.
Alternatively, for myself, I like to write it this way. I prefer shorter codes:
private static int countEm(int[] array, boolean odd)
{
int numEven = 0;
for(int i=0; i< array.length; i++)
if(array[i] % 2 == 0 )
numEven++;
return odd?array.length-numEven:numEven;
}
I prevent using data structures like array list because when I see such questions, I know what are the only things you are allowed to use.
I think this would be the best way to do that:
import java.util.ArrayList;
import java.util.List;
public class EvensAndOdds {
public static List<Integer> getOdds(int[] numbers){
List<Integer> odds = new ArrayList<>();
for(int i = 0; i < numbers.length; i++){
if((numbers[i]%2) != 0){
odds.add(numbers[i]);
}
}
return odds;
}
public static List<Integer> getEvens(int[] numbers){
List<Integer> evens = new ArrayList<>();
for(int i = 0; i < numbers.length; i++){
if((numbers[i]%2) == 0){
evens.add(numbers[i]);
}
}
return evens;
}
public static void main(String[] args){
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
List<Integer> evens = getEvens(numbers);
List<Integer> odds = getOdds(numbers);
System.out.println("Evens: ");
for(Integer even: evens){
System.out.print(even.toString() + " ");
}
System.out.println("");
System.out.println("Odds: ");
for(Integer odd: odds){
System.out.print(odd.toString() + " ");
}
}
}
What about ;):
public class EvenOddSorter {
public void sort(int[] numbers) {
Arrays.sort(numbers,new Comparator<int>() {
#Override
public int compare(int i, int y) {
if(i % 2 == 0)
return -1;
if(y % 2 == 0)
return 1;
return 0;
}
});
}
}
then extract odds and evens from your array by finding the first odd number and using
int[] evens = Arrays.copyOfRange(numbers, 0, numberOfFirstOdd);
int[] odds = Arrays.copyOfRange(numbers, numberOfFirstOdd, numbers.length)
;)
You are creating a new array with too many initial items - hence the zeros at the end. Your getAllEvens() method could look more like:
public static int[] getAllEvens(int[] array)
{
int numberEvens = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
numberEvens++;
}
}
int[] evens = new int[numberEvens]; // This has changed
int count = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
evens[count] = array[i];
count++;
}
}
return evens;
}
This creates a new array with exactly the number of items you are about to populate it with.
Edit: To address your comment, here is my main() method and the output from the method above.
public static void main(String[] args)
{
int[] input =
{
2, 4, 6, 8, 10, 12, 14,
1, 2, 3, 4, 5, 6, 7, 8, 9,
2, 10, 20, 21, 23, 24, 40, 55, 60, 61
};
int[] evens = getAllEvens(input);
System.out.println(Arrays.toString(evens));
}
Which gives
[2, 4, 6, 8, 10, 12, 14, 2, 4, 6, 8, 2, 10, 20, 24, 40, 60]
I feel like the answer so simple but I just can't figure out what it is. I have an multidimensional array such as this:
int [][] number =
{{ 10, 15, 11, 13, 72, 87, 266},
{ 50, 65, 80, 94, 12, 134, 248},
{ 1, 2, 1, 9, 1, 39, 26},
{ 13, 20, 76, 4, 8, 72, 28},
{ 2, 1, 29, 2, 12, 907, 92},
{ 16, 4, 308, 7, 127, 1, 52}
};
I'm trying to add up all the integers in the each array index and display it at the end so what I thought up of is this
int total=0;
for (int k=0;k<6;k++){
for (int i=0;i<7;i++){
total=number[k][i]+total;}}
System.out.println(total);
What I noticed is that it will add up all the numbers in the entire array. But how do I stop it at the end of each index?
Your question is not clear . But from what I understood you must do
for (int k=0;k<6;k++){
int total=0;
for (int i=0;i<7;i++){
total=number[k][i]+total;}
System.out.println(total);}
It will print sum of all rows
Couldn't the loop be like this:
for (int k = 0; k < 6; k++) {
int total = 0;
for (int i = 0; i < 7; i++) {
total += number[k][i];
}
System.out.println(total);
}
Assuming I get what you mean by stop it at the end of each index.
And better should it be if you parametrize your loops to fit in each dimension length:
for (int k = 0; k < number.length; k++) {
int total = 0;
for (int i = 0; i < number[k].length; i++) {
total += number[k][i];
}
System.out.println(total);
}