FakeItEasy AssignsOutAndRefParameters - lazily? - fakeiteasy

I'm trying to fake a call to a method with an out parameter, with a ReturnsLazily with some basic logic in it. Ideally, I could assign a value via AssignsOutAndRefParameters based on the ReturnsLazily. However, AssignsOutAndRefParameters only accepts a value up front when the expression is compiled, is there any 'Lazily' type behavior that I'm missing?
Random r = new Random();
int[] value = new int[] { 1 };
A.CallTo(() => loader.TryLoad(A<int>.Ignored, out value))
.WithAnyArguments()
.ReturnsLazily((int key, int[] inValue) =>
{
List<int> result = new List<int>();
if (key > 0)
{
for (int i = 0; i < r.Next(100); i++)
{
result.Add(r.Next());
}
}
value = result.ToArray();
return result.Count > 0;
})
.AssignsOutAndRefParameters(value); //Assigns [1], instead of [r,a,n,d,o,m,i,n,t,s]

Update As #Crutt knows, FakeItEasy 1.22.0+ has AssignsOutAndRefParametersLazily, which supports exactly the desired behaviour:
Random r = new Random();
int[] value = new int[] { 1 };
A.CallTo(() => loader.TryLoad(A<int>.Ignored, out value))
.WithAnyArguments()
.ReturnsLazily((int key, int[] inValue) => key > 0)
.AssignsOutAndRefParametersLazily((int key, int[] inValue) =>
{
List<int> result = new List<int>();
if (key > 0)
{
for (int i = 0; i < r.Next(100); i++)
{
result.Add(r.Next());
}
}
return new object[] { result.ToArray() };
});
WAS:
No, I think you've found a hole where some functionality could be.
This appears not to be supported as of FakeItEasy 1.21.0.
I've created Issue 319 over at GitHub to track it.

Related

Traversing a game reel matrix column by column from left to right

I have a 3x5 matrix that acts as a game reel. First, I search through the game symbols that I am interested in (let's call them wild clones) and then I search through their children (to locate the game object that has the animation) and then I activate those animations.
private IEnumerator EnableWilds(float delayBetweenWildsAppear)
{
WildSymbol[] wilds = FindObjectsOfType<WildSymbol>();
GameObject[] symbols = new GameObject[wilds.Length];
for (int i = 0; i < wilds.Length; i++)
{
symbols[i] = wilds[i].gameObject;
}
for (int i = 0; i < symbols.Length; i++)
{
if ( symbols[i].name.Contains("(Clone)") )
{
int reelIndex = symbols[i].GetComponentInParent<GameReel>().ReelIndex;
int indexOnReel = symbols[i].GetComponent<WildSymbol>().IndexOnReel;
// ??
for (int j = 0; j < symbols[i].transform.childCount; j++)
{
if ( symbols[i].transform.GetChild(j).gameObject.name.Contains("MM_wild") )
{
symbols[i].transform.GetChild(j).gameObject.SetActive(true);
yield return new WaitForSeconds(delayBetweenWildsAppear);
}
}
}
}
}
I started thinking about how I can activate those wilds starting from the top left corner, and coming down the reel and moving on to the next reel and animating the wilds from top to bottom, etc...
So, I realized I need to get each symbol's reel index (i.e. column number) and index on reel (i.e. position on the reel) so I go Reel1 and then wild clone 1 and 2 and 3, and then Reel2 followed by wild clone 1 and 2 and 3, and so on...
I am trying to do this where I have put a // ?? but at this point, I am a bit lost, conceptually. I cannot figure out how to perform tghis traversal.
Could someone please help me with this?
Here is how I solved it myself, and then simplified it:
private IEnumerator DisableWilds(float delayBetweenWildsDisappear)
{
WildSymbol[] wilds = FindObjectsOfType<WildSymbol>();
wilds = wilds.Where( (item, index) => item.name.Contains("(Clone)") )
.OrderBy( x => x.GetComponent<WildSymbol>().IndexOnReel )
.OrderBy( x => x.GetComponentInParent<GameReel>().ReelIndex )
.ToArray();
for (int i = 0; i < wilds.Length; i++)
{
for (int j = 0; j < wilds[i].transform.childCount; j++)
{
if (wilds[i].transform.GetChild(j).gameObject.name.Contains("MM_wild"))
{
wilds[i].transform.GetChild(j).gameObject.SetActive(false);
yield return new WaitForSeconds(delayBetweenWildsDisappear);
}
}
}
}

How to use selection sort in objects and classes

I'm creating two classes called stop watch and random numbers, which I have already done, but I needed to create a test program that would measure the execution time of sorting 100,000 numbers using selection sort. I know how to create a selection sort, I just don't know how to take the random numbers class and put it together with the selection sort, I get the error message "incompatible types random numbers cannot be converted to int" I hope someone can help me.
My random numbers class
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
My test Program
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
Where exactly are you getting "incompatible types random numbers cannot be converted to int" error?
There are multiple issues with the code:
Unconventional naming
size field is in randomnumbers class is used as actual array size in constructor but in createArray it's overshadowed with a parameter of the same name but different type and meaning.
You are not passing any array to selectionSort in Main. This is where I get compile error on your code.
printArray has if (i < 0) condition that is false for all ran1.nextInt() numbers so it will not print anything.
Feeding selectionSort with numbers.createArray(new int[numbers.getSize()]) compiles and ends up sorting the array.

Why subscriptions to IObservables taken from a Collection don't work (and what to do about it)

My goal is to create a bunch of observables from a source observable, so that I can subscribe to them individually.
When I do that manually (that is, creating each subSource manually), things work as expected: the values added to the original source propagate adequately to the subSources.
But when I create them in a loop, adding them to a List<IObservable<T>>, the subscriptions to elements taken from that list don't seem to be working:
class Program
{
static void Main(string[] args)
{
// using Subject for the sake of example
var source = new Subject<int>();
// manually creating each subSource
var source0 = source.Where((t, i) => i % 3 == 0);
var source1 = source.Where((t, i) => i % 3 == 1);
var source2 = source.Where((t, i) => i % 3 == 2);
// creating a List of subsources
List<IObservable<int>> sources = new List<IObservable<int>>();
int count = 3;
for (int i = 0; i < count; i++)
{
sources.Add(source.Where((v, ix) => ix % 3 == i));
}
// subscribing to one subSource from each group
source0.Subscribe(Console.WriteLine); // this works
sources[1].Subscribe(Console.WriteLine); // this doesn't
// feeding data
Observable.Range(0, 20).Subscribe(source);
Console.ReadKey();
}
}
The predicate of your Where clause references the loop variable i.
However, the predicate is tested when a value is published from source - not when the loop is iterated. By the that time, i has reached it's final value 3.
To fix this, create a new variable inside the loop to store the current value of i, and reference that in your Where predicate:
for (int i = 0; i < count; i++)
{
var j = i;
sources.Add(source.Where((v, ix) => ix % 3 == j)); // note use of j here
}
for (int i = 0; i < count; i++)
{
**var j = i;**
sources.Add(source.Where((v, ix) => ix % 3 == j));
}
Closures.

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}