calculating sum of ListRelation range - sum

I have a ListRelation called PLOCs of type:
lrel[loc, int] PLOCs = [<a, calcPLOC(a)> | a <- files];
where files is a set of locations, and calcPLOC calculates an integer based on that location.
Now I want the sum of all the calculated integers. I used 3 different ways to calculate this, and got 2 different answers:
1:
total = 0;
for (<a, b> <- PLOCs) {
total += b;
}
println("total PLOC: <total>"); // returns 23805
2:
total = sum(range(PLOCs));
println("total PLOC: <total>"); // returns 21313
3:
total = (0 | it + b | <a, b> <- PLOCs);
println("total PLOC: <total>"); // returns 23805
Why does the second method return a different result?

The range function from ListRelation "squeezes" out duplicate entries, but keeps their order.

Related

how to perform dynamic subtraction of a list of numbers with a specific value

My idea is to subtract each value from my list through the value of a variable, for example:
var subtraction = 250
var list = mutableListOf(300, 200, 100)
Then, using the 250 of the subtraction variable,
you can dynamically subtract each value of the item,
from the last to the first, so with that 250 the program should return: -> list(300, 50).
Where 250 is subtracted from item 100 (last item) and then "150" remains from the value "250",
and the remaining 150 is subtracted from 200 (second item) and remains 50,
thus zeroing out the value of "250" and the program stop.
Getting (300, 50) -> 50 which comes from 200 (second item).
As if I was going through my list of numbers, subtracting item by item through the value of a variable, from last to first.
Your question still needs further clarification:
What should be the output if subtraction = 700?
What should be the output if subtraction = 600?
What should be the output if subtraction = 100?
The following can be a starting point to solve your question:
fun subtraction() {
var subtraction = 250
var list = mutableListOf(300, 200, 100)
// Loop the list in Reverse order
for (number in list.indices.reversed()) {
subtraction -= list[number] // Subtract the last number
// If subtraction is greater than zero, continue and remove the last element
if (subtraction > 0)
list.removeAt(number)
else {
// It subtraction is less than or equal to zero,
// remove the last element, append the final subtraction result,
// and stop the loop
list.removeAt(number)
list.add(abs(subtraction))
break
}
}
// If the subtraction result is still positive after whole list has been processed,
// append it back to the list
// if (subtraction > 0)
// list.add(subtraction)
println(list)
}
Output
[300, 50]
The question isn't very clear, but as I understand it: OP wants to modify a list of numbers, subtracting a fixed amount from each, and removing those for which the result would be negative.
If so, it can be done very simply:
list.replaceAll{ it - subtraction }
list.removeIf{ it < 0 }
However, instead of mutating the existing list, it would probably be more common to create a new one:
val newList = list.map{ it - subtraction }.filter{ it >= 0 }
Or, if you need to avoid creating a temporary list:
val newList = list.mapNotNull{ (it - subtraction).takeIf{ it >= 0 } }
A solution with foldRight using a Pair as accumulator:
val list = listOf(300, 200, 100)
val subtraction = 250
val result = list
.foldRight(subtraction to emptyList<Int>()) { item, (diff, list) ->
when {
diff > item -> diff - item to emptyList()
else -> 0 to listOf(item - diff) + list
}
}
.second
println(result) // Output: [300, 50]

Valid Triangle: Error getting sum of two sides less then the third?

Getting wrong output While trying to check the validity of a triangle where condition is ** sum of two side should be greater then the third** on 3 random integers between 0 to 20. Below output suggest two sides are greater then the third but showing "Not a valid triangle".
fun main() {
var a = (Math.random() * 20).toInt()
var b = (Math.random() * 20).toInt()
var c = (Math.random() * 20).toInt()
var validTriangle = "length $a,$b,$c"
if (a + b > c && b + c > a && a + c > b) {
println("Valid Triangle")
} else {
println("Not a valid Triangle")
}
println(validTriangle)
The below output suggests sum of two side(13,6) should be > third side(4)
which is 19 so answer should be "valid triangle" but it is not showing that
Output:
Not a valid Triangle
length 13,6,4

Calculate sum of 2D Arrays

I want to write a program to calculate the sum of 2 matrices(2D Arrays) based on the user input.
Two matrices must have an equal number of rows and columns to be added. The sum of two matrices A and B will be a matrix that has the same number of rows and columns as do A and B.
The first line of standard input is a number of rows n and number of columns m of matrix A. Next n lines are A matrix’s elements. The next line after the empty line is a number of rows n and a number of columns m of matrix B. Next n lines are B matrix’s elements.
I want to output the result of a sum of A and B matrices or ERROR message if it’s impossible. The input contains only integers.
Example
Input:
4 5
1 2 3 4 5
3 2 3 2 1
8 0 9 9 1
1 3 4 5 6
4 5
1 1 4 4 5
4 4 5 7 8
1 2 3 9 8
1 0 0 0 1
Output:
2 3 7 8 10
7 6 8 9 9
9 2 12 18 9
2 3 4 5 7
My Code:
package processor
import java.util.*
val scanner = Scanner(System.`in`)
fun main() {
MatrixProcessor().addition()
}
class MatrixProcessor {
private fun createMatrix(): Array<Array<Int>> {
val rows = scanner.nextInt()
val columns = scanner.nextInt()
return Array(rows) {Array(columns) { scanner.nextInt()} }
}
fun addition() {
val firstMatrix = createMatrix()
val secondMatrix = createMatrix()
val sum = Array(4) { IntArray(5) }
for (i in 0 until 4) {
for (j in 0 until 5) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
}
}
printSolution(sum)
}
private fun printSolution(matrix: Array<IntArray>) {
for (array in matrix) {
for (value in array) {
print("$value ")
}
println()
}
}
}
My main problem lies with sum in the addition function since I do not know how to fill it with dynamic row and column size and currently inserted a standard value of 4 and 5.
fun addition() {
val firstMatrix = createMatrix()
val secondMatrix = createMatrix()
val sum = Array(4) { IntArray(5) }
for (i in 0 until 4) {
for (j in 0 until 5) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
}
}
printSolution(sum)
}
It looks like you're storing your matrices in row-major order: you have individual arrays representing rows, and then an outer array holding all the rows.  So the size of the outer array gives you the number of rows, and the size of any of the inner arrays (such as the first) gives you the number of columns.
So you can create the sum like this:
val sum = Array(firstMatrix.size) { IntArray(firstMatrix[0].size) }
for (i in sum.indices)
for (j in sum[0].indices)
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
(I've used .indices instead of an explicit range, for simplicity.)
An alternative approach is to specify the values when creating the arrays, instead of filling them in afterwards.  (It doesn't make too much difference here, as numeric arrays get a default value of 0; but it can simplify things a lot when creating arrays of a non-nullable reference type.)
val sum = Array(firstMatrix.size) { row ->
IntArray(firstMatrix[0].size) { column ->
firstMatrix[row][column] + secondMatrix[row][column]
}
}
The Array() and IntArray() constructors pass the index into the lambda; while the first version ignores it, here we call it row or columns so we can use it to index the arrays we're summing.
The above assumes that all the inner arrays have the same size.  That's probably reasonable in this case, where you've created the arrays yourself — but in general you'd probably want to verify that.
Certainly, it would be a good idea to verify that the two matrices you're adding are the same size, and throw an IllegalArgumentException with a helpful message if not.  Otherwise, you'd either get an ArrayIndexOutOfBoundsException (if the first were larger), or values would get silently truncated (if the second were larger) — both of which would be much harder to track down.
(The underlying issue here is that, like most languages, Kotlin doesn't have true two-dimensional arrays.  What it does have is arrays of arrays, which are more flexible — and therefore more dangerous.  If you were doing this properly, you'd probably wrap the array-of-arrays into your own Matrix class, which would always ensure that the data was properly rectangular, provide access to the row and column counts, and make all the necessary checks.)
From what i've understood your problem is the fact that you must set a fixed size for Array. I suggest you to use ArrayList instead to solve the problem.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/
With this solution you don't need to set a size for sum anymore.
Once you'll use ArrayLists you'll never get back to Arrays.

while loop and variable not changing

function test(num){
var root1 = Math.sqrt(num);
var ind=2;
while(ind<=root1){
if (ind%num==0 && IsPrime(ind)==true) {
num=ind;
}
ind++;
}
return num;
}
Hi, in this code the function must return the largest prime factor of a given number, but the function returns the same number
For example: test(123) returns 123
You have two problems:
You want to check if num can be divided by ind, not the other way round. The test for that would be: num % ind == 0.
You should not re-use the num variable for the result. That way you overwrite the original number and the result will be wrong. Declare a new variable, for instance, result.

Count the number of null value per column with pentaho

I've got a csv file that contain more than 60 columns and 2 000 000 lines, I'm trying to count the number of null value per variable (per column) then to do the sum of that new row to get the number total of null value in the entire csv. For example if we got this file in input:
We expect this other file in output:
I know how to count the number of null value per line but, I didn't figure out how to count the number of null value per column.
There has to be a better way to do this, but I made a really nasty JavaScript which does the job.
It has some problems for different column types, as it doesn't set the column type. (It should set all columns to integer, but I don't know if that is possible from JavaScript.)
You have to run Identify last row in a stream first, and save it to the column last (or change the script).
var nulls;
var seen;
if (!seen) {
// Initialize array
seen = 1;
nulls = [];
for (var i = 0; i < getInputRowMeta().size(); i++) {
nulls[i] = 0;
}
}
for (var i = 0; i < getInputRowMeta().size(); i++) {
if (row[i] == null) {
nulls[i] += 1;
}
// Hack to find empty strings
else if (getInputRowMeta().getValueMeta(i).getType() == 2 && row[i].length() == 0) {
nulls[i] += 1;
}
}
// Don't store any values
trans_Status = SKIP_TRANSFORMATION;
// Only store the nulls at the last row
if (last == true) {
putRow(nulls);
}
Please drag and drop below steps in to canvas.
step1: Add constants: create one variable called constant and value = 1
step2: Filter Rows: you have filter null values of all columns.
step3: Group by: here group by field constant variable
aggregates section we have to specify remaining columns like ct_inc.And type is Number of Values (N)
If you have any doubts feel free to ask.
skype_id : panabakavenkatesh