I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-2,-3,4,5},{1,-2,3,-4,5}, {1,-2,3,4,-5}.... or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5}, {1,-2,-3,4,-5}, {1,2,-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!
Related
i have a String "iye" and i want make it distinct and also i have a array ["hi", "bye", "bebe"] and i want to make each element of the array and get the distinct characters only so my array would be like this ["hi", "bye", "be"] an then at last i want to take each element from that distinct array and count how many characters of distinctArray[i] are present in the distinct String "iye" and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g
sample input = "iyee" and ["hi", "bye", "bebe"]
sample ouput = [1, 2, 1]
below is my solution not working for larger inputs
static int[] mathProfessor(String B,String[] a){
List<String> distinct = new ArrayList<String>();
int[] arr = new int[a.length];
// store each value of names array as distinct value
for (int i = 0; i < a.length; i++) {
StringBuilder str = new StringBuilder();
a[i].chars().distinct().forEach(c -> str.append((char) c));
distinct.add(str.toString());
}
// System.out.println("distinct list: " + distinct.toString());
// store the count
int count = 0;
for (int i = 0; i < distinct.size(); i++) {
String s = distinct.get(i);
for (int j = 0; j < B.length(); j++) {
if (s.contains(Character.toString(B.charAt(j))))
count++;
}
arr[i] = count;
count = 0;
}
return arr;
}
static int[] mathProfessor(String b, String[] a) {
b = dist(b);
int count = 0;
String[] arr = new String[a.length];
int[] countArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = dist(a[i]);
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < b.length(); j++) {
if (arr[i].contains(Character.toString(b.charAt(j))))
count++;
}
countArr[i] = count;
count = 0;
}
//System.out.println(Arrays.toString(countArr));
return countArr;
}
public static String dist(String s) {
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (set.add(s.charAt(i)) == true)
sb.append(s.charAt(i));
}
return sb.toString();
}
Using Java 8+ Streams:
static int[] mathProfessor(String b, String[] a) {
var distinctB = dist(b);
System.out.println(distinctB);
var result = new int[a.length];
for(int i=0, j=a.length; i < j; i++) {
result[i] = (int) Arrays.stream(dist(a[i]).split("")).filter(distinctB::contains).count();
}
return result;
}
public static String dist(String s) {
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList(s.split("")));
return String.join("", set);
}
I want to copy the old array to the new one and I want to add the empty elements to the new array
import java.util.Arrays;
public class testArray2D {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}};
// make a one bigger
int add = 3;
a = Arrays.copyOf(a, a.length + add);
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = 1;
}
}
for (int i[] : a) {
System.out.println(Arrays.toString(i));
}
}
}
The expected output is
1 2 3
1 1 1
1 1 1
1 1 1
Why I can't run this?
You need to initialize the new array elements.
import java.util.Arrays;
public class testArray2D {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}};
// make a one bigger
int add = 3;
a = Arrays.copyOf(a, a.length + add);
for (int i = 1; i < a.length; ++i) {
if(a[i] == null) {
a[i] = new int[3];
}
for (int j = 0; j < a[i].length; ++j) {
a[i][j] = 1;
}
}
for (int i[] : a) {
System.out.println(Arrays.toString(i));
}
}
}
If you want to copy existing array to a new array having size larger than the existing array, I would suggest the following.
int[][] source_arr = {{1, 2, 3}};
int add = 3;
int[][] dest_arr = new int[source_arr[0].length+add][source_arr[0].length];
for (int i = 0; i < source_arr.length; i++) {
System.arraycopy(source_arr[i], 0, dest_arr [i], 0, source_arr[i].length);
}
I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;
I am working on a merge sort algorithm. Below is what i have written so far. The problem is when I try and run it to see if it is working I get the index out of bounds error on the if statement I marked with a comment.
Why am I getting index out of bounds on the line I commented next to?
I know what the error means but am unable to decipher why its out of bounds.
public class MergeSort {
public static int mergeSort(int[] list1, int[] list2) {
int[] list3 = new int[list1.length + list2.length];
int smallest1 = list1[0];
int smallest2 = list2[0];
int position1 = 0;
int position2 = 0;
for (int i = 0; i<list1.length + list2.length; i++) {
for (int j =0; j<= list1.length; j++) {
if (list1[j] < smallest1) { //here index out of bouds
smallest1 = list1[j];
System.out.print(list1[j]+"smallest value");
position1 = j;
}
}
for (int l =0; l<= list2.length; l++) {
if (list2[l] < smallest2) {
smallest2 = list2[l];
System.out.print(list2[l]+"smallest value");
position2 = l;
}
}
if (smallest1< smallest2) {
list3[i] = smallest1;
} else if (smallest2< smallest1) {
list3[i] = smallest2;
}
}
//print the array
for (int l =0; l<= list2.length; l++) {
System.out.print("new array 3" + list3[l]);
}
return 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list1 = {17, 22, 35, 42, 60};
int[] list2 = {9, 14, 66};
int[] list3;
mergeSort(list1, list2);
}
}
Indexes run from 0, this means when list1.length = 5 then the index can be 0 through 4
change
for (int j =0; j<= list1.length; j++)
to
for (int j =0; j < list1.length; j++)
This is because your for loop condition is <=. Try to use <
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