I need help with a code where I have to put the number "7" at the front of the array using a random array of numbers. I use Math.random to generate the random numbers in each index. In any of these indexes, a number 7 may be generated.
import java.util.Arrays;
public class NumberShifter {
public static int[] Array(){
int[] array = new int[20];
int max = 10;
int min = 1;
int rand = 0;
int range = max - min +1;
for(int t = 0;t<=array.length-1;t++) {
rand = (int)(Math.random() * range) + min;
array[t] = rand;
}
return array;
}
}
Here's an example output for the code I have displayed (its all random numbers)
[9, 6, 3, 4, 4, 10, 7, 5, 2, 10, 3, 1, 8, 7, 4, 4, 10, 5, 9, 1]
There are two sevens in this array that have been generated randomly.
I would like to have the output where the sevens are at the front.
[7, 7, 3, 4, 4, 10, 9, 5, 2, 10, 3, 1, 8, 6, 4, 4, 10, 5, 9, 1]
How would I write the rest of my code so that I can achieve this?
P.S. I'm also in high school, so I'm sorry if I get something wrong!
Iterate the elements of the array and if they are 7 swap them with the next element at the beginning of the array, using another variable to keep track of the next index for swapping.
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 7) {
int tmp = array[i]; // actually not needed, we know it's 7
array[i] = array[index];
array[index] = tmp; // or just 7
index++;
}
}
I would actually start at the end and reserve the front for the sevens.
public static int[] Array() {
int[] array = new int[20];
int max = 10;
int min = 1;
int rand = 0;
int range = max - min + 1;
int sevensGoHere = 0;
for (int t = array.length - 1; t >= sevensGoHere;) {
rand = (int) (Math.random() * range) + min;
if (rand == 7) {
array[sevensGoHere++] = rand;
}
else {
array[t--] = rand;
}
}
return array;
}
By doing it on the fly you don't need to rearrange the array.
Related
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]
I've been trying to complete this problem for about 2 days now since it's the weekend and I can't contact any tutors at my school. I have made a loop that finds the highest value in a non-empty array and then swaps the lowest index of the highest number in that array with the last value in the array.
For example
swapLargest([1, 7, 5, 7, 4, 2]) → [1, 2, 5, 7, 4, 7]
but running it comes out as
[1, 7, 5, 7, 2, 4]
here is my code
int[] swapLargest(int[] a) {
int max = Integer.MIN_VALUE;
for(int i = 1; i <a.length; i++){ // starting from 0
if(a[i] > max){
max = a[i];
max = i;
}
}
int temp = a[max];
a[max]=a[a.length-1];
a[a.length-1] = temp;
return a;
}
and finally a link to the problem: http://codingbat.com/prob/p227094 if you'd like to test your results with mine. so far this would pass 4/11 tests.
I'm really new to programming, any tips would be appreciated.
Thanks!
You can store index of the max value in separate variable:
int[] swapLargest(int[] a) {
int max = Integer.MIN_VALUE;
int maxI = 0 ;
for(int i = 0; i < a.length; i++){
if(a[i] > max){
max = a[i];
maxI = i;
}
}
int temp = a[maxI];
a[maxI]=a[a.length-1];
a[a.length-1] = temp;
return a;
}
I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two ways that I have tried.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
Arrays.sort(data);
System.out.println("Minimum = " + data[0]);
System.out.println("Maximum = " + data[data.length - 1]);
}
}
This version complies but doesn't run.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
}
return maxValue;
{
public static int getMinValue (int[] numbers) {
int minValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
}
}
return minValue;
}
This version just throws me a bunch of errors in compiling. Any help is greatly appreciated.
Ok, I've kinda fixed your code. Actually your mistake was that you have not been traversing all the cells of your multidimensional array.
So, I've added additional loop into getMinValue/getMinValue methods and fixed array elements addressing.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
};
System.out.println(getMaxValue(data));
System.out.println(getMinValue(data));
}
public static int getMaxValue(int[][] numbers) {
int maxValue = numbers[0][0];
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers[j].length; i++) {
if (numbers[j][i] > maxValue) {
maxValue = numbers[j][i];
}
}
}
return maxValue;
}
public static int getMinValue(int[][] numbers) {
int minValue = numbers[0][0];
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers[j].length; i++) {
if (numbers[j][i] < minValue ) {
minValue = numbers[j][i];
}
}
}
return minValue ;
}
}
I have a more fun solution using Java 8 :)
IntSummaryStatistics stats = Arrays.stream(data).flatMapToInt(Arrays::stream).collect(Collectors.summarizingInt(Integer::intValue));
int max = stats.getMax();
int min = stats.getMin();
It's a different solution than yours, obviously. But it does the same thing. To begin with, we convert the 2D array into a Stream of ints. In order to do this first we need to call flatMapToInt. We do this to stream all the elements in the array in a flat way. Imagine if we just start using a single index to iterate over the whole 2D array. It's something like that. Once we have converted the array into a stream, we will use IntSummaryStatistics in order to reuse the same stream for both min and max.
Your problem is: You are sorting the array of int arrays instead of sorting each individual int in each int array.
To solve this: Loop through each int array in the array of int arrays.
Instructions for finding the maximum and minimum of a 2D int array using Arrays.sort():
Declare a 2D int array to sort called data.
Declare two ints, one to hold the maximum value, the other the minimum value.
The initial value of the maximum should be Integer.MIN_VALUE and the initial value of the minimum should be Integer.MAX_VALUE to make sure that negative values are handled.
Loop through data from 0 to data.length:
Sort data[i]
Check if the first value of data[i] is less than the minimum and change it if it is.
Check if the last value of data[i] is greater than the maximum and change it if it is.
Output your result.
Example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++) {
Arrays.sort(data[i]);
if(data[i][0] < minimum) minimum = data[i][0];
if(data[i][data[i].length - 1] > maximum) maximum = data[i][data[i].length - 1];
}
System.out.println("Minimum = " + maximum);
System.out.println("Maximum = " + minimum);
}
}
package array;
public class Max_number {
// 2 5 7 9
// 3 6 8 1
public static void main (String[] arg) {
int a[][] = {{2,5,7,9},{3,6,8,1}};
int max=a[0][0];
for (int i=0; i<2; i++) //row
{
for (int j=0; j<4; j++) //coloum
{
if(a[i][j]>max)
{
max=a[i][j];
}
}
}
System.out.println("maximum number is"+max);
}
}
Say I have 10 integer variables, x1 to x10.
I have an integer array, as follows:
Int[] countup = new Int[10];
I would like to specify the elements of the array as follows:
countup[0] = x1;
countup[1] = x1 + x2;
countup[2] = x1 + x2 + x3;
And so on until countup[9] is the sum of x1 to x10.
I could do this manually if it was just 10 elements, but in the actual program I'm writing, there's over 100 elements of the array. Is there any way to set the variables of this array quickly?
A for loop is your best bet, simply put your 10 (or 100) integers into an array of it's own, then loop over your second array referencing indexes of the first array:
int[] xNumbers = { x1, x2, x3, ... x10 };
int[] countup = new int[10];
//Set the 0 index so we don't have to do extra check inside the for loop
//for out-of-bounds exception
countup[0] = xNumbers[0];
for (int i = 1; i < 10; i++) {
//countup[i-1] is why we set index 0 outside of the loop
countup[i] = xNumbers[i] + countup[i-1];
}
since countup[i-1] is the sum of the previous numbers, the previous additions are already done for you. In case you don't know what a for loop is, more information can be found here
Succinctly:
int[] xNums = { /*your x numbers here*/ };
int[] resultArray = new int[xNums.length];
for(int n = 0; n < xNums.length; n++)
{
for(int i = 0; i <= n; i++)
{
resultArray[n]+=xNums[i];
}
}
Hope that makes sense!
I wanted to find a way to do it in Java 8, and the other answer is probably better:
Here's what I have, but it seems redundant and a waste of time, but I'm unfamiliar with Java 8:
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = arr.length;
for (int i = 1; i < length; i++) {
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, i + 1)));
arr[i] = Arrays.stream(Arrays.copyOfRange(arr, 0, i + 1)).sum();
}
System.out.println(Arrays.toString(arr));
}
arr[9] is [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
I believe I also interpreted the question differently. I think he wanted in index[i] the sum of all previous elements.
If my interpretation of your question is correct, to do it without Java 8, using 2 loops:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = array.length;
for(int i = 1; i < length; i++) {
int sumSoFar = 0;
for(int j = 0; j <= i; j ++) {
sumSoFar += array[j];
}
array[i] = sumSoFar;
}
This question already has answers here:
Adding a number to midpoint af an array [closed]
(3 answers)
Closed 9 years ago.
The code below I have set the midpoint of the array to five but now I want to move the midpoint to the very end and as it moves to the end the other numbers will go to the left to fill the gap. No arraylists aloud.
int mid = length/2;
for (int i = array.length-1 ; i> mid; i--) {
array[i] = array[i-1];
}
array[mid] = 5;
Something like this?
int mid = array.length/2;
for (int i = mid; i < array.length-1; i++)
{
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
public static void main(String[] args) {
int array[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int mid = array.length / 2;
array[mid] = 5;
// my code starts here...
int aux = mid; // aux isn't necessary if you can lost mid value
int backup = array[mid]; // save the middle value
for (; aux < array.length - 1; aux++) { //starting at middle until the end of array
// current pos receives the next value;
array[aux] = array[aux + 1];
}
array[array.length - 1] = backup; // restore the middle value at the end;
}
That code transforms [1, 2, 3, 4, 5, 6, 7, 8, 9] in [1, 2, 3, 4, 6, 7, 8, 9, 5].
Is it that you want?