I have the following 2d array
int [][] array = {{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
{20, 21, 22, 23, 24, 25, 26, 27, 28, 29},
{30, 31, 32, 33, 34, 35, 36, 37, 38, 39},
{40, 41, 42, 43, 44, 45, 46, 47, 48, 49},
{50, 51, 52, 53, 54, 55, 56, 57, 58, 59},
{60, 61, 62, 63, 64, 65, 66, 67, 68, 69},
{70, 71, 72, 73, 74, 75, 76, 77, 78, 79},
{80, 81, 82, 83, 84, 85, 86, 87, 88, 89},
{90, 91, 92, 93, 94, 95, 96, 97, 98, 99}};
I have this code to find the sum of all the values in the array. How can I modify it to add only the diagonal values starting at 0 (0+11+22+33 etc.)?
public static int arraySum(int[][] array)
{
int total = 0;
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[row].length; col++)
total += array[row][col];
}
return total;
}
Since the diagonals are at perfect square you only need one loop to add the diagonals.
Adding diagonal from orgin:
public static int arraySum(int[][] array){
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row];
}
return total;
}
Add both diagonals:
Adding diagonal from orgin: (note it adds the center twice..you can subtract one if needed)
public static int arraySum(int[][] array){
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row] + array[row][array.length - row-1];
}
return total;
}
public static int arraySum(int[][] array)
{
int total = 0;
for (int index = 0; index < array.length; index++)
{
total += array[index][index];
}
return total;
}
This of course assumes m x m for the dimensions.
Here is my solution -
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
for(int a_i=0; a_i < n; a_i++){
for(int a_j=0; a_j < n; a_j++){
a[a_i][a_j] = in.nextInt();
}
}
int l_sum = 0;
for(int i = 0; i<n ; i++){
l_sum+=a[i][i];
}
int r_sum = 0;
for(int j = 0; j<n ; j++){
r_sum+=a[j][n-1-j];
}
int sum = l_sum + r_sum;
System.out.println(sum);
}
}
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int leftStartDiagnol = 0;
int rightStartDiagnol = n;
int leftTotal = 0;
int rightTotal = 0;
int a[][] = new int[n][n];
for (int a_i = 0; a_i < n; a_i++) {
for (int a_j = 0; a_j < n; a_j++) {
a[a_i][a_j] = in.nextInt();
}
}
for (int a_i = 0; a_i < n; a_i++) {
boolean leftNotFound = true;
boolean rightNotFound = true;
rightStartDiagnol = --rightStartDiagnol;
for (int a_j = 0; a_j < n; a_j++) {
if (leftStartDiagnol == a_j && leftNotFound) {
leftTotal = leftTotal + a[a_i][a_j];
leftNotFound = false;
}
if (rightStartDiagnol == a_j && rightNotFound) {
rightTotal = rightTotal + a[a_i][a_j];
rightNotFound = false;
}
}
leftStartDiagnol = ++leftStartDiagnol;
}
int data = leftTotal - rightTotal;
System.out.println(Math.abs(data));
}
}
Here is my solution. Check out it.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
int total1=0;
int total2=0;
for(int a_i=0; a_i < n; a_i++){
for(int a_j=0; a_j < n; a_j++){
a[a_i][a_j] = in.nextInt();
}
total1+= a[a_i][a_i];
total2+=a[a_i][n-1-a_i];
}
System.out.println(Math.abs(total1-total2));
}
}
import java.io.*;
import java.util.*;
public class DigArraySum {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=Integer.parseInt(s.nextLine()); //array size
int[][] a=new int[n][n]; // new array
for (int i=0;i<n;i++) {
String str=s.nextLine();
String[] tempArray=str.split(" ");
for (int j=0;j<n;j++) {
a[i][j]=Integer.parseInt(tempArray[j]);
}
}
int x=0;//primary diagonal sum
int y=0;//secondary diagonal sum
int sum=0;//total sum
for (int i=0;i<n;i++) {
x += a[i][i];
}
for (int p=0;p<n;p++) {
int k=a.length-p-1;
y+=a[p][a.length-p-1];
k+=-1;
}
sum=x-y;
System.out.println(Math.abs(sum));
}
}
Explanation:
for example 3*3 matrix:
3// Array size
11 2 4
4 5 6
10 8 -12
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Total Sum: |4 + 19| = 23
Solution in PHP. The logic is exactly the same what is already posted here. It's only in PHP that's different.
<?php
$handle = fopen ("php://stdin", "r");
function diagonalDifference($a) {
$sumA = [];
$sumB = [];
$n = count($a);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($i === $j) {
$sumA[] = $a[$i][$j];
}
if ($i + $j == count($a) -1 ) {
$sumB[] = $a[$i][$j];
}
}
}
$sum1 = array_sum($sumA);
$sum2 = array_sum($sumB);
return abs($sum1 - $sum2);
}
fscanf($handle, "%i",$n);
$a = array();
for($a_i = 0; $a_i < $n; $a_i++) {
$a_temp = fgets($handle);
$a[] = explode(" ",$a_temp);
$a[$a_i] = array_map('intval', $a[$a_i]);
}
$result = diagonalDifference($a);
echo $result . "\n";
?>
The solution is:
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row] + array[row][array.length - row - 1];
}
System.out.println("FINAL ANSWER: " + total);
Here is the code which I did to find the sum of primary diagonal numbers and secondary diagonal numbers
static int diagSum(int[][] arr) {
int pd=0;
int sd=0;
int sum=0;
for(int i=0;i<=arr.length-1;i++){
pd=pd+arr[i][i];
}
for (int k=0,l=arr.length-1; k<arr.length&&l>=0 ; k++,l--) {
sd=sd+arr[k][l];
}
sum=pd+sd;
return sum;
}
difference between the sums of its diagonals in kotlin :
val total = (0 until array.size).sumBy { array[it][it] - array[it][array.size - it - 1] }
if you want absolute difference:
return Math.abs(total)
public class matrix {
public static void main(String[] args) {
int sum=0;
int a[][]= new int[][]{{2,3,4},{4,5,6},{5,5,5}};
for(int i=0;i<=2;i++)
{
sum=sum+a[i][i];
}
System.out.println(sum);
}
}
If you want to add both diagonal in a 2d array then here is my program.
static int diagonalDifference(int[][] arr) {
int r = arr.length;
int sum1 = 0;
int sum2 = 0;
int j=0;
for(int i=0;i<r;i++){
sum1 = sum1 + arr[i][j];
j++;
}
j--;
for(int i=0;i<r;i++) {
sum2 = sum2 + arr[i][j];
j--;
}
int sum=sum1+sum2;
return sum;
}
If you want to add both diagonal in a 2d array then here is a solution:
int j = row_col_size-1;
for (int i = 0; i < intArray.length; i++) {
sum_left += intArray[i][i];
sum_right += intArray[i][j];
j--;
}
Although this post is very old. Providing my solution. This might be useful for someone
func diagonalDifference(arr [][]int32) int32 {
return int32(math.Abs(float64(arraySumPrimary(arr)) - float64(arraySumSecondary(arr))) )
}
func arraySumPrimary(arr [][]int32) int32{
var total int32 =0
for row :=0; row < len(arr) ; row ++{
total = total + arr[row][row]
}
return total
}
func arraySumSecondary(arr [][]int32) int32{
var total int32 =0
x := len(arr)-1
y := 0
for x >=0 && y < len(arr){
total = total + arr[x][y]
x--
y++
}
return total
}
Related
int[] bestTime = {50, 73, 72, 75, 71, 56, 61, 60, 62, 68, 70, 50, 70};
assume if n = 6, expected return = {50, 50, 56, 60, 61, 62}
this is what i have so far, i know there are lots of mistakes. any suggestions is much appreciated.
public static int[] bestRun(int n) {
int[] best = bestTime[0];
for(int i = 0; i <= bestTime.length; i++ ) {
if(bestTime[i] <= best) {
best = bestTime[i];
best++;
} return best;
}
if(best.length == n) {
return best;
}
return null;
}
Build an IntStream of your bestTime array, sort them, limit using n, convert to array and return:
public static int[] bestRun(int n) {
return IntStream.of(bestTime).sorted().limit(n).toArray();
}
You can do the task also using classic for loops. But then you need to implement the sorting yourself. Something like below should give you a how this can be accomplished:
static int[] bestTime = {50, 73, 72, 75, 71, 56, 61, 60, 62, 68, 70, 50, 70};
public static void main(String args[]) throws IOException{
int[] best = bestRun(6);
System.out.println(Arrays.toString(best));
}
public static int[] bestRun(int n) {
//copy your bestTime array
int[] copy = new int[bestTime.length];
for(int i = 0; i < copy.length; i++){
copy[i] = bestTime[i];
}
//sort copy
for (int i = 0; i < copy.length; i++) {
for (int j = i+1; j < copy.length; j++) {
int temp = 0;
if(copy[i] > copy[j]) {
temp = copy[i];
copy[i] = copy[j];
copy[j] = temp;
}
}
}
//fill your result array
int[] result = new int[n];
for(int i = 0; i < n; i++){
result[i] = copy[i];
}
return result;
}
This code is about algorithms and datastructures. This code runs perfectly and i just have some questions on it because it seems like i don't understand two points. So my questions for that is:
which informations are in the countingArray?
how often is the while loop executed?
public class CountingSort {
public static void main(String[] args) {
int[] m1 = { 1, 17, 3, 1, 4, 9, 4, 4 };
System.out.println("unsorted:");
output(m1);
int min1 = rangeMin(m1);
int max1 = rangeMax(m1);
countingSort(m1, min1, max1);
System.out.println("sorted:");
output(m1);
int[] m2 = { -1, 13, 3, -1, -4, 9, -4, 4 };
System.out.println("unsorted:");
output(m2);
int min2 = rangeMin(m2);
int max2 = rangeMax(m2);
countingSort(m2, min2, max2);
System.out.println("sorted:");
output(m2);
}
public static void output(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ", ");
}
System.out.println();
}
public static int rangeMin(int[] a) {
int minimum = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < minimum)
minimum = a[i];
}
return minimum;
}
public static int rangeMax(int[] array) {
int maximum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maximum)
maximum = array[i];
}
return maximum;
}
public static void countingSort(int[] array, int rangeMin, int rangeMax) {
int[] countingArray = new int[rangeMax - rangeMin + 1];
for (int i : array) {
countingArray[i - rangeMin]++;
}
int c = 0;
for (int i = rangeMin; i <= rangeMax; i++) {
while (countingArray[i - rangeMin] > 0) {
array[c] = i;
c++;
countingArray[i - rangeMin]--;
}
}
}
}
CountingSort has O(n) time and space complexity. You iterate (i.e. use for loop) twice.
public class CountingSort {
public static void main(String... args) {
proceed(1, 17, 3, 1, 4, 9, 4, 4);
System.out.println("---");
proceed(-1, 13, 3, -1, -4, 9, -4, 4);
}
public static void proceed(int... arr) {
System.out.print("unsorted: ");
print(arr);
countingSort(arr);
System.out.print("sorted: ");
print(arr);
}
public static void print(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(i -> String.format("%2d", i))
.collect(Collectors.joining(",")));
}
public static void countingSort(int... arr) {
int min = Arrays.stream(arr).min().orElse(0);
int max = Arrays.stream(arr).max().orElse(0);
// contains amount of number in the unsorted array
// count[0] - amount of min numbers
// count[count.length - 1] - amount of max numbers
int[] count = new int[max - min + 1];
for (int i : arr)
count[i - min]++;
// fill source array with amount of numbers
for (int i = 0, j = 0; i < count.length; i++)
for (int k = 0; k < count[i]; k++, j++)
arr[j] = min + i;
}
}
here is the integer array given to me 111,77, 88, 44, 32, 11, 13, 25, 44 I need to sort & display only the odd elements of the array .
I had tried solving it using loops and if condition
i had expected the output as 11 13 25 77 111
import java.lang.reflect.Array;
public class oddsortSolution {
public static void main(String args[]) {
int n[] = { 111, 77, 88, 44, 32, 11, 13, 25, 44 };
int i = 0;
int temp = 0;
while (i < n.length) {
if (n[i] % 2 != 0) {
for (int j = i + 1; j < n.length; j++) {
if (n[j] > n[i]) {
n[j] = temp;
n[j] = n[i];
n[i] = temp;
}
}
}
}
System.out.println(n[1]);
}
}
You basically need to keep track of your odd array size, increment it every time you find an odd value, determine if the value should be swapped somewhere in the existing array (ranging from 0 to oddArraySize) and insert it in the correct position. Try the following code,
public class oddsortSolution {
public static void main(String args[]) {
int n[] = { 111, 77, 88, 44, 32, 11, 13, 25, 44 };
int oddArraySize = 0;
for (int i = 0;i < n.length; i++) {
if (n[i] % 2 != 0) {
oddArraySize++;
for (int j = 0; j < oddArraySize; j++) {
if (j == oddArraySize - 1) {
n[j] = n[i];
} else if (n[j] > n[i]) {
int temp = n[j];
n[j] = n[i];
n[i] = temp;
}
}
}
}
int[] oddArray = Arrays.copyOfRange(n, 0, oddArraySize);
System.out.println( Arrays.toString( oddArray ));
}
}
I am supposed to create an algorithm that sorts according to these steps:
Method 1
Select the lowest number in the list and swap with the first number.
Select the lowest number in the list and swap with the second number.
Start checking from the second number.
Select the lowest number in the list and swap with the third number.
Start checking from the third number.
Select the lowest number in the list and swap with the fourth number.
Start checking from the fourth number.
Repeat…until you reach the last number.
Currently, this is the code I have come up with:
public static void method1() {
int low = 999;
int index = 0;
int safe;
int[] num = new int[] { 33, 22, 8, 59, 14, 47, 60, 27 };
for(int i = 0; i < num.length; i++) {
if(low > num[i]) {
low = num[i];
index = i;
}
}
for (int i = 0; i < num.length; i++) {
safe = num[i];
num[i] = num[index];
low = 999;
for(int j = (i+1); j < num.length; j++) {
if(low > num[j]) {
low = num[j];
}
}
}
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] +", ");
}
}
The output looks like this:
run:
8, 8, 8, 8, 8, 8, 8, 8,
BUILD SUCCESSFUL (total time: 0 seconds)
Why am I only getting values of 8 in the output? As this is homework, please don't tell me the answer. I would only like guidance, thanks!
EDIT:
Code now looks like this:
int low = 999;
int index = 0;
int safe;
int[] num = new int[] { 33, 22, 8, 59, 14, 47, 60, 27 };
for(int i = 0; i < num.length; i++) {
if(low > num[i]){
low = num[i];
index = i;
}
}
for (int i = 0; i < num.length; i++) {
safe = num[i];
num[i] = num[index];
low = 999;
for(int j = (i+1); j < num.length; j++) {
if(low > num[j]){
low = num[j];
index = j;
}
}
}
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] +", ");
}
System.out.println("");
Which gives me an output of:
run:
8, 8, 8, 14, 14, 27, 27, 27,
BUILD SUCCESSFUL (total time: 0 seconds)
The date for this homework has been and gone, but thought I would add some step-by-step methodology.
The way I would approach this is to break it down into small steps. Each step should be a method or function.
1. The first step is to find the smallest number in the array, starting from N.
So the method for this would be:
private int findLowestStartingAtNth( int n ) {
int lowest = Integer.MAX_VALUE;
for( int i = n ; i < numbers.length ; i++ ) {
if( numbers[i] < lowest ) {
lowest = numbers[i];
}
}
return lowest;
}
2. Then we need to swap two arbitrary numbers in an array.
This is quite simple:
private void swapNumbers( int i, int j ) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
3. But if we want the output of findLowestStartingAtNth() to feed into the input of swapNumbers(), then we need to return the index not the number itself.
So the method from step 1. is altered to be:
private int findLowestStartingAtNth( int n ) {
int lowest = Integer.MAX_VALUE;
int index = n;
for( int i = n ; i < numbers.length ; i++ ) {
if( numbers[i] < lowest ) {
lowest = numbers[i];
index = i;
}
}
return index;
}
4. Let's use what we have to achieve step one
Select the lowest number in the list and swap with the first number.
The first number is the zero-th in the array.
int numbers = new int[] {33, 22, 8, 59, 14, 47, 60, 27};
int found = findLowestStartingAtNth( 0 );
swapNumbers(0, found);
5. We have a pattern. Start checking from 1st, swap with 1st. Start checking from 2nd, swap with 2nd. Start checking with X, swap with X.
So let's wrap this pattern in a further method:
private int[] numbers = new int[] {33, 22, 8, 59, 14, 47, 60, 27};
private void sort() {
for( int i = 0 ; i < numbers.length ; i++ ) {
int j = findLowestStartingAtNth( i );
swapNumbers(i, j);
}
}
6. Finally, wrap it in a class, and trigger it from main() method. See how clear the code is because it is broken into small steps.
The entire resulting class would be:
public class Method1 {
public static void main(String[] args) {
Method1 m = new Method1();
m.numbers = new int[] {33, 22, 8, 59, 14, 47, 60, 27};
m.sort();
System.out.println(Arrays.toString(m.numbers));
}
private int[] numbers;
private int findLowestStartingAtNth( int n ) {
int lowest = Integer.MAX_VALUE;
int index = n;
for( int i = n ; i < numbers.length ; i++ ) {
if( numbers[i] < lowest ) {
lowest = numbers[i];
index = i;
}
}
return index;
}
private void swapNumbers( int i, int j ) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
private void sort() {
for( int i = 0 ; i < numbers.length ; i++ ) {
int j = findLowestStartingAtNth( i );
swapNumbers(i, j);
}
}
}
I am using first array to store all database of numbers where some numbers are duplicates.
I have went through this array to see which items are duplicated and am adding index of duplicated items to second array.
Now, I must loop through first array and add all but duplicated values to third array (assuming that we know which fields are duplicated).
But how to do this correctly? I can't make it stop adding every item from first array to third array.
Assuming I can't use HashSet().
The purpose of this is to demonstrate how to move one array to other with removed duplicated in O(N) time complexity.
Input numbers: 00, 11, 11, 22, 33, 44, 55, 55, 66, 77, 88, 99
Output which index are duplicated: 1, 2, 6, 7
Output I get: 00, 11, 11, 22, 33, 44, 55, 55, 66, 77, 88, 99 (same as the input)
Code:
public void dups()
{
int[] b = new int[100];
int[] c = new int[100];
int k = 0;
int n = 0;
int p = 0;
for (int i = 0; i < nElems; i++)
for (int j = 0; j < nElems; j++)
if(a[j].equals(a[i]) && j != i)
b[k++] = i;
for (int l = 0; l < k; l++)
System.out.print(b[l] + " ");
for (int m = 0; m < nElems; m++)
if (m != b[p + 2])
c[m] = (Integer) a[n++];
System.out.print("\n");
for (int o = 0; o < nElems; o++)
System.out.print(c[o] + " ");
}
It can be done in a simpler way:
Set<Integer> uniqueSet = new HashSet<Integer>();
uniqueSet.addAll(list);
//not uniqueSet contains only unique elements from the list.
The reason it works is that a Set cannot contain duplicates. So while adding elements to a Set, it ignores those that are duplicates.
You can use a HashSet instead of Array to store all database of numbers.
After that use Collections.toArray() to get your desired Array.
I see that the question got edited and we don't want to use HashSet anymore.
Anyways, your problem is already answered here, Algorithm: efficient way to remove duplicate integers from an array
Instead of marking all duplicates you could mark all that have already been seen earlier.
Instead of:
for (int i = 0; i < nElems; i++)
for (int j = 0; j < nElems; j++)
if(a[j].equals(a[i]) && j != i)
b[k++] = i;
Use something like:
for (int i = 0; i < nElems; i++)
for (int j = i+1; j < nElems; j++)
if(a[j].equals(a[i]))
b[k++] = j;
You should then see:
Output which index are duplicated: 2, 7
Which should be much easier to work with.
Here's a working solution - although I wouldn't do it this way:
public class Test {
Integer[] a = {00, 11, 11, 22, 33, 44, 55, 55, 66, 77, 88, 99};
int nElems = a.length;
public void dups() {
int[] b = new int[100];
int[] c = new int[100];
int k = 0;
int n = 0;
int p = 0;
for (int i = 0; i < nElems; i++) {
for (int j = i + 1; j < nElems; j++) {
if (a[j].equals(a[i])) {
b[k++] = j;
}
}
}
for (int l = 0; l < k; l++) {
System.out.print(b[l] + " ");
}
for (int m = 0; m < nElems; m++) {
if (m != b[p]) {
c[n++] = a[m];
} else {
p += 1;
}
}
System.out.print("\n");
for (int o = 0; o < nElems - k; o++) {
System.out.print(c[o] + " ");
}
}
public static void main(String args[]) {
new Test().dups();
}
}
which prints:
2 7
0 11 22 33 44 55 66 77 88 99
I don't know if this is what you were looking for. But it removes duplicate. Give it a shot,
int[] b = { 00, 11, 11, 22, 33, 44, 55, 55, 66, 77, 88, 99 };
List<Integer> noDups = new ArrayList<Integer>();
Boolean dupliceExists;
for (int i = 0; i < b.length; i++) {
dupliceExists = Boolean.FALSE;
for (Integer integ : noDups) {
if (Integer.valueOf(b[i]).equals(integ)) {
dupliceExists = Boolean.TRUE;
//Get index if you need the index of duplicate from here
}
}
if (!dupliceExists) {
noDups.add(b[i]);
}
}
for (int i = 0; i < noDups.size(); i++) {
System.out.println(noDups.get(i));
}
I am going to coding for copying non-duplicate elements from one Array to another Array.
/*
* print number of occurance of a number in an array beside it
*
* */
class SpoorNumberOfOccuranceInArray{
public static void main(String[] args){
int[] arr={65,30,30,65,65,70,70,70,80};
int[] tempArr=new int[arr.length];//making size compatible to source Array.
int count=0;
for(int i=0;i<arr.length;i++){
int temp=arr[i];
for(int j=0;j<tempArr.length;j++){
if(temp==tempArr[j]){ //Comparing the Availability of duplicate elements in the second Array.---------
break;
}
else{ //Inserting if value is not in the second Array.---------------
if( tempArr[j]==0){
tempArr[j]=temp;
break;
}//end if
}//end else
}//end if
}//end for
for(int i=0;i<tempArr.length;i++){
for(int j=0;j<arr.length;j++){
if(tempArr[i]==arr[j])
count++;
}
System.out.println(tempArr[i]+" "+count);
count=0;
}
}
}