I have to make a program that extract every 3th element from array. So far i have made the basic array, but im stuck at extracting every 3th element into separate array. How can i do that?
public static void main(String[] args) {
int min = -100;
int max = 100;
int[] array = new int[201];
for( int i = 0; i < array.length; i++) {
array[i] = min + (int)(Math.random()*((max - min) + 1));
To fill in a new array (named array2) with every 3rd item from your array:
int[] array2 = new int[array.length / 3];
int k = 2;
for(int j = 0; j < array2.length; j++) {
array2[j] = array[k];
k += 3;
}
just make your for loop jump by three:
int[] newArray = new int[array.length / 3];
for (int i = 2 ; i < array.length ; i+=3) {
newArray[i/3] = array[i];
}
Related
If I have array like [1,2,3,4] and k = 3 then output should be [1,2,3][2,3,4] which is in this order. The idea is to get subarray with k elements and then the next to start from the next element and also to have k elements
I can't think of a way to do it more generic for any value of k.
final int arr[] = new int[] { 1, 2, 3, 4 };
final int max = 2;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
for (int k = 0; k < max; k = k + 2) {
System.out.println(i + "" + j);
}
}
}
You can extract parts of an array by calling Arrays.copyOfRange() method:
int[] arr = {1, 2, 3, 4};
int k = 3;
int numberOfResults = arr.length - k + 1;
for (int i = 0; i < numberOfResults; i++) {
int[] result = Arrays.copyOfRange(arr,i,i+k);
System.out.println(Arrays.toString(result));
}
My code is supposed to take the random number generated in the random method and sort them but it's only giving me one number.
My program is a random number generator that is supposed to make 1000 numbers that I can sort but my code only inserts one number into the array.
public static void main(String[] args) {
// write
int max = 1000;
int min=0;
int range = max - min + 1;
// generate random numbers within 1 to 10
for (int i = 0; i < 1000; i++) {
int rand = (int) (Math.random () * range) + min;
System.out.println ( rand );
int array[] = {rand};
int size = array.length;
for ( i = 0; i < size - 1; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min = j;
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
for (int k = 0; k < size; i++) {
System.out.print(" " + array[i]);
}
}
}
You need to break your program into separate steps:
Insert all the random numbers into the array
Sort the array
Print the contents of the array
Few problems I noticed:
Since you want to generate 1000 numbers from 1-10, max and min should have values of 10 and 1, respectively.
array should be declared before you start inserting values. It should also have a fixed size of 1000.
Your bubble sort algorithm also had some errors which led to incorrect output. If you wish to sort the array from greatest to least instead, simply change the > to < in the condition of the if statement.
I also decided to use Arrays.toString() to print the array instead of the loop.
public static void main(String[] args) {
int max = 10;
int min = 1;
int range = max - min + 1;
int size = 1000;
int[] array = new int[size];
for (int i = 0; i < size; i++) {
int rand = (int) (Math.random() * range + min);
array[i] = rand;
}
int temp = 0;
for (int i = 0; i < size; i++) {
for (int j = 1; j < size - i; j++) {
if (array[j - 1] > array[j]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
System.out.println(Arrays.toString(array));
}
your code will result an ArrayIndexOutException. below is the code change from your code ,i dont change too much so you can compare them and find your mistakes,wish good :D
public static void main(String[] args) {
int max = 1000;
int min=0;
int range = max - min + 1;
int[] array = new int[range];
// generate random numbers within 1 to 10
for (int i = 0; i < 1000; i++) {
int rand = (int) (Math.random () * range) + min;
array[i] = rand;
}
int size = array.length;
for (int i = 0; i < size; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min1 = j;//here min1
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
for (int k = 0; k < size; k++) {
System.out.print(" " + array[k]);
}
}
let me explain it more clearly,in the OP's code there has some questions,two majors:
one:
for ( i = 0; i < size - 1; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min = j;
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
will never run,because the array size is 1 ,so the for loop phrase will be ignore without running(mean for(int i = 0; i < 0; i++){....}).
two:
for (int k = 0; k < size; i++) {
System.out.print(" " + array[i]);
}
beacause the array size is 1,so when array[1] will throw index out exception.so the outermost loop will just run once then throw a exception.
:D
I have trouble converting negative array elements into absolute. So far ive made array containing both negative and positive, but i have to convert them into absolute, in order to calculate array square root. Any suggestions?
public static void main(String[] args) {
int min = -100;
int max = 100;
int[] array = new int[201];
for (int i = 0; i < array.length; i++) {
array[i] = min + (int) (Math.random() * ((max - min) + 1));
//System.out.println(array[i]);
}
int[] array2 = new int[array.length];
for (int j = 2; j < array.length; j += 3) {
array2[j] = array[j];
//System.out.println(array[j]);
double[] result = new double[array2.length];
for (int i = 0; i < array2.length / 3; i++) {
array2[i] = Math.abs(i);
result[j] = Math.sqrt(array[j]);
System.out.println(array[i]);
}
your third-last line is wrong, you need:
result[j] = Math.sqrt(array2[j]);
You're calling Math.abs() on i (the index) not on the array element. Also, you are storing the result of abs into array2[i] and then calling Math.sqrt() on a different array and element (array[j]). Also check if your for loop indexes iterate the fields in the way you want (to me the for loop statements seem somewhat strange).
You have to clearly describe your intentions,
it is no clear that you want each third element of the array and not every one of them.
However there are multiple ways to achive the result.
You can create a List to store square root of each third element
List<Double> result1 = new ArrayList<>();
for (int j = 2; j < array.length; j += 3) {
result1.add(Math.sqrt(Math.abs(array[j])));
}
If you would like to use arrays make it like so
double[] result2 = new double[array.length / 3];
for (int j = 2; j < array.length; j += 3) {
result2[j / 3] = Math.sqrt(Math.abs(array[j]));
}
In both examples we call Math.abs to get the absolute value and Math.sqrt to get square root.
Here is the full code
public static void main(String args[])
{
int min = -100;
int max = 100;
int[] array = new int[201];
for (int i = 0; i < array.length; i++) {
array[i] = min + (int) (Math.random() * ((max - min) + 1));
}
List<Double> result1 = new ArrayList<>();
for (int j = 2; j < array.length; j += 3) {
result1.add(Math.sqrt(Math.abs(array[j])));
}
double[] result2 = new double[array.length / 3];
for (int j = 2; j < array.length; j += 3) {
result2[j / 3] = Math.sqrt(Math.abs(array[j]));
}
System.out.println(result1);
System.out.println(Arrays.toString(result2));
}
I have a java code where X is a 2D array and a loop to add data to it. The code is as follows:
public static void main(String [] args0
{
int[] len = new int[3];
double[][] X = null;
double[][] vec = null;
for (int i = 0; i < 3; i++)
{
System.out.println("Enter the len" +(i+1)+":");
len[i] = in.nextInt();
if(i == 0)
{
vec = new double [1][len[i] + 1];
X = new double[1][vec[0].length];
for(int k = 0; k < vec[0].length - 1; k++)
{
Xi[0][k] = 0;
}
Xi[0][ve1[0].length-1] = 1;
}
else
{
vec = new double [1][len[i] + 1];
X = new double[1][vec[0].length];
for(int k = 0; k < vec[0].length - 1; k++)
{
X[0][k] = 0;
}
X[0][vec[0].length-1] = 1;
}
}
}
When I print X, I need it have appended the values added when i=0 and when i>0. But it prints only the value of what is supposedly the final iteration. How do I make it print the data of all iterations appended to the end of data added during each iteration? I understand that since I am creating a new double[][] in each iteration, the value of gets overwritten. But how do i fix it?
You have correctly identified that with X = new double[1][vec[0].length]; you are always overriding the result from previous iterations. In order to fix it, you need to move the initialization out of the for loop. Here is an example of how you can do that:
public static void main(String [] args) {
int[] len = new int[3];
double[][] X = new double[3][];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Enter the len " +(i+1)+":");
len[i] = in.nextInt();
X[i] = new double[len[i]];
for (int j = 0; j < len[i] - 1; j++) {
X[i][j] = 0;
}
X[i][len[i] - 1] = 1;
}
in.close();
}
As you can see, the array X is initialized in the beginning with size 3, since it will always hold 3 one-dimensional arrays in your case. However, you can initialize the size dynamically as well. You don't need the vec variable, because you can always access the length that was just read and stored in len. In fact, you don't need the len array as well, since it stores information that is anyways contained in X:
public static void main(String [] args) {
double[][] X = new double[3][];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Enter the len " + (i+1) + ":");
X[i] = new double[in.nextInt()];
for (int j = 0; j < X[i].length - 1; j++) {
X[i][j] = 0;
}
X[i][X[i].length - 1] = 1;
}
in.close();
}
I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.