Swift: for-in with two values - objective-c

I started learning C some weeks ago and today I started learning Swift. The code is the following:
import Foundation
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 8, 16, 25],
]
var largest = 0;
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number;
}
}
}
println(largest);
Why do I need kind in the for-in thingy? For "Prime", "Square", ..., right? Can I work with that somehow, too?
“Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.”
How do I build that in?

import Foundation
var largest = 0;
var largestKind: String?;
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 8, 16, 25],
]
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number;
largestKind = kind;
}
}
}
println("The number \(largest) is from the type \(largestKind)");
That's my solution at the moment. However, the output is
The number 25 is from the type Optional("Square")
How do I get rid of the 'Optional("")? I just want the word Square. I tried removing the question mark (var largestKind: String?; to var largestKind: String;) but I get an error doing that.

For those who have the same question, this is another solution I've found. var largestKind is still optional because of String? but the exclamation mark at the end \(largestKind!) makes it possible to access the value without having that optional stuff around the actual content.
import Foundation
var largest = 0;
var largestKind: String?;
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 8, 16, 25],
]
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number;
largestKind = kind;
}
}
}
println("The number \(largest) is from the type \(largestKind!).");

Related

How do you keep the every kth element of a list in Ramda?

How do you filter out every kth element of a list with Ramda?
input = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = keepKth(input, 3)
output = [1, 4, 7]
This seemed to work:
let k = 3;
let Kth = (value, index) => (index % k == 0)
let filterKth = R.addIndex(R.filter)(Kth);
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let output = filterKth(input);
A variation based on Scott's comment:
const keepEvery = k => compose(pluck(0), splitEvery(k));
keepEvery(3)([1, 2, 3, 4, 5, 6, 7, 8, 9]);
//=> [1, 4, 7]
https://ramdajs.com/docs/#pluck
https://ramdajs.com/docs/#splitEvery
Probably not the cleanest, but point free.
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const whitelist = R.addIndex(R.reject)(R.flip(R.modulo(R.__, 3)));
console.log(
whitelist(data),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.js" integrity="sha512-MEPRnhl9ArIiZuk6ikVrLzYxQm8ov1Ngkn4kIUO82hwpD7d+cwXQ7+isupqVgZ6HHtAEBDMff8eUhzixwEBSbA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
And here is another method based on R.unfold. The seed is the index (initial 0), and it's incremented by k on every iteration.
const { curry, unfold } = R
const fn = curry((k, arr) => unfold(n => n < arr.length && [arr[n], n + k], 0))
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const result = fn(3, data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.js" integrity="sha512-MEPRnhl9ArIiZuk6ikVrLzYxQm8ov1Ngkn4kIUO82hwpD7d+cwXQ7+isupqVgZ6HHtAEBDMff8eUhzixwEBSbA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

How can I generate a random Verhoeff number in Apache Jmeter?

Need to pass a new Verhoeff Number every time I execute my script. The already used Verhoeff number is rejected by my application, as a business validation. Can someone help with the script for this?
The Java algorithm implementation is available at the Wikipedia page
In JMeter it's recommended to use Groovy for scripting so you will need to amend it to look like:
/**
* #see <ahref="http://en.wikipedia.org/wiki/Verhoeff_algorithm" > More Info</a>
* #see <ahref="http://en.wikipedia.org/wiki/Dihedral_group" > Dihedral Group</a>
* #see <ahref="http://mathworld.wolfram.com/DihedralGroupD5.html" > Dihedral Group Order 10</a>
* #author Colm Rice
*/
public class Verhoeff {
// The multiplication table
static int[][] d = new int[][]
{
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
[2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
[3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
[4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
[5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
[6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
[7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
[8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
};
// The permutation table
static int[][] p = new int[][]
{
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
[5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
[9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
[4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
[7, 0, 4, 6, 9, 1, 3, 2, 5, 8]
};
// The inverse table
static int[] inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];
/*
* For a given number generates a Verhoeff digit
*
*/
public static String generateVerhoeff(String num) {
int c = 0;
int[] myArray = stringToReversedIntArray(num);
for (int i = 0; i < myArray.length; i++) {
c = d[c][p[((i + 1) % 8)][myArray[i]]];
}
return Integer.toString(inv[c]);
}
/*
* Validates that an entered number is Verhoeff compliant.
* NB: Make sure the check digit is the last one.
*/
public static boolean validateVerhoeff(String num) {
int c = 0;
int[] myArray = stringToReversedIntArray(num);
for (int i = 0; i < myArray.length; i++) {
c = d[c][p[(i % 8)][myArray[i]]];
}
return (c == 0);
}
/*
* Converts a string to a reversed integer array.
*/
private static int[] stringToReversedIntArray(String num) {
int[] myArray = new int[num.length()];
for (int i = 0; i < num.length(); i++) {
myArray[i] = Integer.parseInt(num.substring(i, i + 1));
}
myArray = reverse(myArray);
return myArray;
}
/*
* Reverses an int array
*/
private static int[] reverse(int[] myArray) {
int[] reversed = new int[myArray.length];
for (int i = 0; i < myArray.length; i++) {
reversed[i] = myArray[myArray.length - (i + 1)];
}
return reversed;
}
}
and in order to call this and to store the result into a JMeter Variable you need to use vars shorthand to JMeterVariables class instance, something like:
vars.put('myVar', Verhoeff.generateVerhoeff("your-source-number-here"))
and then you will be able to refer the generated value as ${myVar} where required.

Compare two numbers, ramdajs

Say I have two functions
const getMeanPrice = R.....
const getLastPrice = R...
What functions should I use to check if one value is greater than the other?
const isLastPriceHigherThanMeanPrice = R. ???
There is R.gt https://ramdajs.com/0.22.1/docs/#gt
But it only accepts two numbers. Need something that accepts two functions. Like
R.somefunc(getMeanPrice, getLastPrice)(prices) => boolean
lift converts a function that operates on values into one that operates on containers of values. For instance,
lift (gt) ([8, 1, 6], [3, 5, 7])
//=> [8 > 3, 8 > 5, 8 > 7, 1 > 3, 1 > 5, 1 > 7, 6 > 3, 6 > 5, 6 > 7]
//=> [true, true, true, false, false, false, true, true, false]
A function that returns a certain type can be thought of as a container of elements of that type, so if we lift R.gt, it will also operate on functions. Thus:
// Dummy implementations
const getMeanPrice = R.mean
const getLastPrice = R.last
const isLastPriceHigherThanMeanPrice = R.lift (R.gt) (getLastPrice, getMeanPrice)
console .log ([
[4, 5, 6],
[6, 5, 4],
[8, 6, 7, 5, 3, 0, 9],
[8, 6, 7, 5, 3, 0]
].map(a => `[${a.join(', ')}] ==> ${isLastPriceHigherThanMeanPrice(a)}`).join('\n'))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
lift will work with any Apply type, meaning one that has lawful ap and map functions defined. This include arrays, functions, and many other useful types, such as most implementations of Maybe, Either, Future, and many others.

Mapping set of keys to a matching list of lists

What is an idiomatic way to map keys to a matching list of lists? An example - given:
val s = listOf(1, 9)
val u = listOf(listOf(1, 2, 3), listOf(1, 4, 7), listOf(1, 5, 9))
I would like to have a Map<Int, List<List<Int>>> such that every key in s is mapped to a list of lists containing that key:
{1=[ [1, 2, 3], [1, 4, 7], [1, 5, 9] ], 9=[ [1, 5, 9] ]}
The following:
s.groupBy({ it }, { x -> u.filter { it.contains(x) } })
produces:
{1=[[[1, 2, 3], [1, 4, 7], [1, 5, 9]]], 9=[[[1, 5, 9]]]}
which is not quite right and it isn't clear how to flatten the result to the expected shape.
I would recommend associateWith and use it like this:
s.associateWith { num -> u.filter { list -> num in list } }
Output:
{1=[[1, 2, 3], [1, 4, 7], [1, 5, 9]], 9=[[1, 5, 9]]}
I recommended associate at first, but you can shorten the code even further if you use associateWith. Thanks to Abhay Agarwal who recommended it.
Update
You just need to flatten the values of the result Map.
val w = s.groupBy({ it }, { x -> u.filter { it.contains(x) } })
.mapValues { it.value.flatten() }
My solution map the first collection to pairs from each element to the list where it appears, and then groupBy the result list.
Example
val w = s.map { elem -> Pair(elem, u.filter { list -> elem in list }) }
.groupBy ({ it.first }, { it.second })
.mapValues { it.value.flatten() }
check(w[1] == listOf(listOf(1, 2, 3), listOf(1, 4, 7), listOf(1, 5, 9)))
check(w[9] == listOf(listOf(1, 5, 9)))
println(w)
Output
{1=[[1, 2, 3], [1, 4, 7], [1, 5, 9]], 9=[[1, 5, 9]]}
Idiomatic to me would be s.groupBy(....) The answer by #Omar Mainegra - s.groupBy(...).mapValues( flatten ) absolutely works but it looks like a hack where the initial result needs some extra massaging.
The issue is with the implementation of groupBy and more specifically with groupByTo:
public inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<V>() }
list.add(valueTransform(element))
}
return destination
}
The implementation wraps the values associated with a key in a list because in general multiple values can be associated with a key which is not the case here
where values in s are unique which means that groupBy is the wrong function to use. The right function is associateWith:
s.associateWith { x -> u.filter { it.contains(x) } }
produces:
{1=[[1, 2, 3], [1, 4, 7], [1, 5, 9]], 9=[[1, 5, 9]]}

Can help make array with only odd numbers from array in Kotlin

I need help. I trying make array only with odd numbers but I don't want use arraylist because I only want array.
Input array like this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I am trying to get odd only array like : [1, 3, 5, 7, 9]
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val arraylist = arrayListOf<Int>()
for(i in 0..array.size - 1) {
if(array[i] % 2 != 0)
arraylist.add(array[i])
}
val oddarray = arraylist.toArray()
Why not just use filter:
import java.util.Arrays;
fun main(args: Array<String>) {
val numbersArray = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val oddArray = numbersArray.filter{ it % 2 != 0 }.toTypedArray()
print(Arrays.toString(oddArray)) // [1, 3, 5, 7, 9]
}