So, I am trying to take an array input of 6,7,34,7,6 and create a method to have the ouput be 6 6 7 7 34 34 7 7 6 6.
How would i go about that?
So far I have:
public int [] twice (int[] ary)
int [] A = new int [ary.length * 2]
A [0] = 6;
A [1] = 7;
A [2] = 34;
A [3] = 7;
A [4] = 6;
But i don't know where to go from there.
Try this one:
public static int[] twice(int[] ary) {
int[] A = new int[ary.length * 2];
for(int i=0, j=0;j<ary.length;i=i+2,j++) {
A[i] = A[i+1] = ary[j];
}
return A;
}
Just use two for loops
{
for (int i=0;i<5;i++) System.print(ary[i]);
for (int i=0;i<5;i++) System.print(ary[4-i]);
}
If u want to add the values at the end
// Java program explaining System class method - arraycopy()
import java.lang.*;
import java.util.Arrays;
public class NewClass
{
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = Arrays.copyOf(s, s.length*2);
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 0;
dest_arr = d;
destPos = s.length;
len = s.length;
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
}
public static int [] twice (int[] ary)
{
int [] A = new int [ary.length * 2];
//take 2 variables one to point input array and 1 for output array
int c = 0;
for(int n: ary) {
//put each element of input array twice in output array
A[c] = A[c+1] = n;
c += 2;
}
//return output array
return A;
}
As your input values look like they're sorted and then you put the same values to destination array again in descending order, you might want to try attempt with sorting your input first depending on what you want to achieve:
public int [] twice(int[] ary) {
int[] temporary = new int[ary.length];
for (int i = 0; i < ary.length; i++) { // copying ary to temporary
temporary[i] = ary[i];
}
Arrays.sort(temporary); // sorting temporary in ascending order
int[] result = new int[ary.length * 2]; // creating double sized result array
for(int i = 0; i < temporary.length; i++) { // copying sorted contents of temporary at the beginning of result array
result[i] = temporary[i];
}
int j = 0 ;
for(int i = result.length - 1; i >= result.length / 2; i--) { // inserting contents of temporary from the end of result array to the middle ("from right to left")
result[i] = temporary[j++];
}
return result; // returning result array
}
Related
public class Power {
public static void main(String[] args) {
int base = 3, exponent = 9;
int[] result = new int[10];
System.out.println(result);
while (exponent != 0)
{
result * base = result;
--exponent;
System.out.println(result);
}
}
}
What I would like this code to do is be able to Multiply 1*3 to make 3, put it inside of the array, and multiply it again, and so on and so forth. Basically, it needs to output, 1 3 9 27 81 243 729 2187 6561 19683. How can I store it inside of the array, and also multiply it again?
You could keep a result variable and continue saving it to an array:
int index = 0;
int[] result = new int[10];
int current = 1;
for (int i = 0; i < result.length; ++i) {
result[i] = current;
current *= 3;
}
System.out.println(Arrays.asString(result));
result[0] = 1;
System.out.print(result[0] + " ");
for (int i = 1; i < n; i++) {
result[i] = result[i-1]*3;
System.out.print(result[i] + " ");
}
Let n be one less than the number of entries you want to print.
Your first problem is that assignments need the name on the left side, and the expression on the right side; replace result * base = result; by result = result * base;.
Secondly, result is an array. You’re trying to treat it as a single number.
Thirdly, if you want to fill an array, use a for loop instead of what you currently have:
final int base = 3;
final int[] result = new int[10];
result[0] = 1;
for (int i = 1; i < result.length; i++) {
result[i] = result[i - 1] * base;
}
I need some help inserting the number 8 into an array that gives me random values. The array must be in order. For example if I had an array of (1,5,10,15), I have to insert the number 8 between 5 and 10. I am having a problem on how I can figure our a way to find the index where 8 will be placed because the array is random, it can be anything. Here is my code so far :
public class TrickyInsert {
public static void main(String[] args) {
int[] mysteryArr = generateRandArr();
//print out starting state of mysteryArr:
System.out.print("start:\t");
for ( int a : mysteryArr ) {
System.out.print( a + ", ");
}
System.out.println();
//code starts below
// insert value '8' in the appropriate place in mysteryArr[]
int[] tmp = new int[mysteryArr.length + 1];
int b = mysteryArr.length;
for(int i = 0; i < mysteryArr.length; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
mysteryArr = tmp;
any tips? thanks!
Simply add the number then use Arrays.sort method,
int b = mysteryArr.length;
int[] tmp = new int[b + 1];
for(int i = 0; i < b; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
mysteryArr = Arrays.sort(tmp);
In your example the random array is sorted. If this is the case, just insert 8 and sort again.
Simply copy the array over, add 8, and sort again.
int[] a = generateRandArr();
int[] b = Arrays.copyOf(a, a.length + 1);
b[a.length] = 8;
Arrays.sort(b);
int findPosition(int a, int[] inputArr)
{
for(int i = 0; i < inputArr.length; ++i)
if(inputArr[i] < a)
return i;
return -1;
}
int[] tmpArr = new int[mysteryArr.length + 1];
int a = 8; // or any other number
int x = findPosition(a, mysteryArr);
if(x == -1)
int i = 0;
for(; i < mysteryArr.length; ++i)
tmpArr[i] = mysteryArr[i];
tmpArr[i] = a;
else
for(int i = 0; i < mysteryArr.length + 1; ++i)
if(i < x)
tmpArr[i] = mysteryArr[i];
else if(i == x)
tmpArr = a;
else
tmpArr[i] = mysteryArr[i - 1];
I will suggest using binary search to find the appropriate index. Once you locate the index, you can use
System.arraycopy(Object src, int srcIndex, Obj dest, int destIndex, int length)
to copy the left half to your new array (with length one more than the existing one) and then the new element and finally the right half. This will stop the need to sort the whole array every time you insert an element.
Also, the following portion does not do anything.
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
since int b = mysteryArr.length;, after setting int i =b ;, i<mysteryArr.length; will be false and hence the line inside this for loop will never execute.
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
private double[] myNumbers = {10, 2, 5, 3, 6, 4};
private double[][] result;
private double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
//System.out.println(result[0] +" "+ result[1]);
return result;
}
I'm trying to sort the one dimensional array in to a matrix, where numbers between 4 - 8 are in one, and all other numbers are in the other.
1) You're not initializing result[][]. You will get a NullPointerException.
Either loop through myNumbers, count the number of values for each category, and create result[][], or push your values into an ArrayList<Double>[2] and use List.toArray() to convert back to an array.
2) result[][] is declared outside your method. While technically valid, it's generally poor form if there is not a specific reason for doing so. Since you're already returning double[][] you might want to declare a double[][] inside your function to work with and return.
I'm not following exactly what you want, but this should allow your code to work.
class OneDimToTwoDim {
public static void main(String[] args) {
// declare myNumbers one dimensional array
double[] myNumbers = {10, 2, 5, 3, 6, 4};
// display two dimensional array
for (int x = 0; x < myNumbers.length; x++) {
System.out.print("[" + myNumbers[x] + "] "); // Display the string.
}
// pass in myNumbers argument for derp parameter, and return a two dimensional array called resultNumbers
double[][] resultNumbers = OneDimToTwoDim.divideNumbers(myNumbers);
System.out.println(); // Display the string.
System.out.println(); // Display the string.
for (int x = 0; x < resultNumbers.length; x++) {
for (int y = 0; y < resultNumbers[x].length; y++) {
System.out.print("[" + resultNumbers[x][y] + "] "); // Display the string.
}
System.out.println(); // Display the string.
}
}
private static double[][] divideNumbers(double[] derp) {
// declare result to be returned
double[][] result = new double[2][derp.length];
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
return result;
}
}
Your result array isn't initialized. Are you getting null pointer exceptions? Is that the problem?
private static double[] myNumbers = {10, 2, 5, 3, 6, 4};
private static double[][] result = new double[2][myNumbers.length];
private static double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
result[0] = Arrays.copyOfRange(result[0],0,k);
result[1] = Arrays.copyOfRange(result[1],0,j);
return result;
}
I currently have this piece of code.
Currently what happens is that two arrays are being taken in, and all possible sequential combinations of the indices of Array A are being stored as a list of seperate arrays, each of which are the same size as array B. Currently to do this sizeA has to be smaller than sizeB.
import java.util.*;
public class Main {
public static void main(final String[] args) throws FileNotFoundException {
ArrayList<String> storeB= new ArrayList();
ArrayList<String> storeA = new ArrayList();
Scanner scannerB = new Scanner(new File("fileB"));
Scanner scannerA = new Scanner(new File("fileA"));
while(scannerB.hasNext()) {
String b = scannerB.next();{
storeB.add(b);
}
}
while(scannerA.hasNext()) {
String A = scannerA.next();{
storeA.add(A);
}
}
final int sizeA = storeA.size();
final int sizeB = storeB.size();
final List<int[]> combinations = getOrderings(sizeA-1, sizeB);
for(final int[] combo : combinations) {
for(final int value : combo) {
System.out.print(value + " ");
}
System.out.println();
}
}
private static List<int[]> getOrderings(final int maxIndex, final int size) {
final List<int[]> result = new ArrayList<int[]>();
if(maxIndex == 0) {
final int[] array = new int[size];
Arrays.fill(array, maxIndex);
result.add(array);
return result;
}
// creating an array for each occurence of maxIndex, and generating each head
//recursively
for(int i = 1; i < size - maxIndex + 1; ++i) {
//Generating every possible head for the array
final List<int[]> heads = getOrderings(maxIndex - 1, size - i);
//Combining every head with the tail
for(final int[] head : heads) {
final int[] array = new int[size];
System.arraycopy(head, 0, array, 0, head.length);
//Filling the tail of the array with i maxIndex values
for(int j = 1; j <= i; ++j)
array[size - j] = maxIndex;
result.add(array);
}
}
return result;
}
}
I'm wondering, regardless of sizeA and sizeB, how do I modify this to create arrays which are double sizeB and duplicate each index value. So if we had:
[0,1,1,2]
this would become:
[0,0,1,1,1,1,2,2]
i.e duplicating each value and placing it next to it.
Also, how would I eliminate recursion in this so that rather than producing all possible combinations, on each call, a single array at random is produced rather than a list of arrays.
Thank you.
So if we had: [0,1,1,2] this would become: [0,0,1,1,1,1,2,2] i.e duplicating each value and placing it next to it.
public int[] getArray(int originSize) {
// Create a array double the size of originSize
int[] result = new int[originSize * 2];
// Iterate through 0 to originSize - 1 (This are your indicies)
for (int i = 0, j = 0; i < originSize; ++i, j+=2)
{
// i is the index to insert into the new array.
// j holds the current position in the new array.
// On the first iteration i = 0 is written onto the
// position 0 and 1 in the new array
// after that j is incremented by 2
// to step over the written values.
result[j] = i;
result[j+1] = i;
}
return result;
}
int[] sizeB_double = new int[sizeB.length()*2];
for(int i = 0; i<sizeB_double; i+=2)
{
sizeB_double[i] = sizeB[i/2];
if(sizeB_double.length > (i+1))
sizeB_double[i+1] = sizeB[i/2];
}