This question already has answers here:
How can I co-sort two Vecs based on the values in one of the Vecs?
(1 answer)
What is the correct type to use for an array index?
(1 answer)
Do I have to use a usize to access elements of a vector?
(1 answer)
What must I cast an `u8` to in able to use it as an index in my vector?
(2 answers)
Mutably borrow one struct field while borrowing another in a closure
(2 answers)
Closed 1 year ago.
I have a struct of the shape
pub struct ExampleData {
data: Vec<u32>,
data_ids: Vec<u32>,
}
Sample data
{data: [9,8,7], data_ids: [0,1,2]}
I want to sort the data_ids vector based on the values of the data vector and I have implemented the following method:
impl ExampleData {
pub fn sorting(&mut self) {
self.data_ids.sort_by(|a, b| self.data[a].cmp(self.data[b]));
}
}
The above code does not work:
error[E0277]: the type `[u32]` cannot be indexed by `&u32`
--> src/lib.rs:10:38
|
10 | self.data_ids.sort_by(|a, b| self.data[a].cmp(self.data[b]));
| ^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `SliceIndex<[u32]>` is not implemented for `&u32`
= note: required because of the requirements on the impl of `Index<&u32>` for `Vec<u32>`
What am I doing wrong here?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I know algorithm of lexicographic order but in this question we can have repetition of character non-consecutively.And this make me confused.
A good string s is the one which:
contains only these letters of the set: [a,b,c]
s[i] != s[i+1]
string aba, bca,cbc is valid but aaa, abb, aab not valid.
Order of set:[a, b, c]
["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"].
Can you help me out with its algorithm.
You can use a recursive algorithm where you pass the last used letter as a forbidden letter for the next selection. The recursive function gets a size argument so it knows how long the strings should be that it should produce. It then iterates every possible character, but excludes the forbidden one, and calls the function recursively, but with the size reduced. The current character now becomes the forbidden character for the recursive call. When that call comes back with results, it prefixes each of those results with the current character, so that effectively they all increase in size by one character. This is repeated for all other characters that are iterated (except the forbidden one). And all these results are collected into one result set (array), and returned.
I assume the set of characters is provided in lexicographic order (otherwise sort it before using the below algorithm), and that the size of the produced strings is also a parameter given to the algorithm.
Here is a simple JavaScript implementation of that idea:
function combis(chars, size, forbidden="") {
if (size == 0) { // base case
return [""];
}
let results = [];
for (let chr of chars) {
if (chr != forbidden) { // Avoid repetition
for (let combi of combis(chars, size-1, chr)) {
results.push(chr + combi); // prefix the returned string
}
}
}
return results;
}
console.log(combis("abc", 3));
It sounds like what you wanna do is to order using Lexicographic order and then filter out the results that you consider invalid.
In your example step 1 will be:
["aaa", "aab", "aac", ...]
then remove what is not valid, and you will get:
["aba", "abc", "aca", ...]
You can just sort your list of strings lexicographically. These would contain strings that are having same consecutive characters. So, before return the result, you could just make another list and loop over the original list while only including the strings that match the above criteria into the new list. Once you iterate the whole list, just return it and that would be your final answer.
For eg. Consider a list -
["cab", "abc", "aca", "acc", "abb", "bbc", "caa", "aab"]
After you sort it -
['aab', 'abb', 'abc', 'aca', 'acc', 'bbc', 'caa', 'cab']
Now you can just loop over this list and only pick the elements that match your criteria. So the final list will be -
['abc', 'aca', 'cab']
Hope your understood the approach.
This question already has answers here:
How do I create a random String by sampling from alphanumeric characters?
(4 answers)
How can I randomly select one element from a vector or array?
(6 answers)
Closed 3 years ago.
I'm trying to make a function using Rust that, given an integer, returns a value of type String.
The main problem I'm facing is creating a random character; once I can do that I can concatenate lots of these characters in a loop or something like that and then return the final string.
I've tried to find way to type cast an integer returned from the random function in the rand crate (as you can do in C++) but this does not seem to be the way to go.
What should I do?
The Rust Cookbook shows how this can be accomplished elegantly. Copied from the link above:
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
fn random_string(n: usize) -> String {
thread_rng().sample_iter(&Alphanumeric)
.take(n)
.collect()
}
If you wish to use a custom distribution that is not available in rand::distributions, you can implement it by following the source code for one of the distributions to see how to implement it yourself. Below is an example implementation for a distribution of some random symbols:
use rand::{Rng, seq::SliceRandom};
use rand::distributions::Distribution;
struct Symbols;
impl Distribution<char> for Symbols {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
*b"!##$%^&*()[]{}:;".choose(rng).unwrap() as char
}
}
This question already has answers here:
What are these three dots in React doing?
(23 answers)
Closed 4 years ago.
I'm putting my hands into reason-react.
In the following code :
let component = ReasonReact.statelessComponent("Component3");
let make = (~name, _children) => {
...component,
render: self => <input type_="checkbox" />,
};
I don't understand what (...) means on line 3.
When I delete it I get an error message :
The record field component can't be found.
If it's defined in another module or file, bring it into scope by:
- Annotating it with said module name: let baby = {MyModule.age: 3}
- Or specifying its type: let baby: MyModule.person = {age: 3}
The representation is called Spread Syntax. This was introduced in ES6.
Definition and example from MDN Docs. Link at the bottom.
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
More details at : Spread Syntax
This question already has answers here:
Passing lists from one function to another in Swift
(2 answers)
Closed 7 years ago.
I am getting a Binary operator '/' cannot be applied to two (Int) operands error when I put the following code in a Swift playground in Xcode.
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
The above was a function calculating the total sum of any numbers.
Below is a function calculating the average of the numbers. The function is calling the sumOf() function from within itself.
func avg(numbers: Int...) -> Float {
var avg:Float = ( sumOf(numbers) ) / ( numbers.count ) //Binary operator '/' cannot be applied to two (Int) operands
return avg
}
avg(1, 2, 3);
Note: I have looked everywhere in stack exchange for the answer, but the questions all are different from mine because mine is involving two Ints, the same type and not different two different types.
I would like it if someone could help me to solve the problem which I have.
Despite the error message it seems that you cannot forward the sequence (...) operator. A single call of sumOf(numbers) within the agv() function gives an error cannot invoke sumOf with an argument of type ((Int))
The error is telling you what to do. If you refer to https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_operators.html
/ Division.
A binary arithmetic operator that divides the number to its left by the number to its right.
Class of operands: integer, real
Class of result: real
The second argument has to be real. Convert it like so. I don't use xcode, but I think my syntax is correct.
var avg:Float = ( sumOf(numbers) ) / Float( numbers.count )