C# Nested Loop not repeating entirely - nested-loops

There is an error somewhere in my nested loops causing the program to not display the prime factorizations of the value when the program increases the value by 1. Does anyone have any ideas what I did wrong? Any assistance would be greatly appreciated.
using System;
using static System.Console;
namespace Primes
{
class Program
{
static void Main(string[] args)
{
int minValue = 15,
maxValue = 21;
int x = minValue,
y = 2;
WriteLine("Prime Factors:");
WriteLine();
for (minValue = x; minValue <= maxValue; minValue++)
{
Write("\n\t{0}", minValue);
if(minValue <= maxValue)
while (x > 2)
{
if (x % y == 0)
{
Write(" : " + Convert.ToString(y));
x = x / y;
}
else
++y;
}
}
ReadLine();
}
}
}

Ok...this is more precise and closer to what you are looking for I believe...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Primes
{
class Program
{
static void Main(string[] args)
{
int minValue = 15,
maxValue = 21;
WriteLine("Prime Factors:");
WriteLine();
while (minValue <= maxValue )
{
int x = minValue;
int y = 2;
Write("\n\t{0}", minValue);
if (minValue <= maxValue)
while (x >= 2)
{
if (x % y == 0)
{
Write(" : " + Convert.ToString(y));
x = x / y;
}
else
++y;
}
minValue++;
}
ReadLine();
}
}
}

Related

How to limit number of elements in a stream responsively?Java8

The problem I am having is turning this block of code into Java8 streams.Basically I have a list of cells that are either dead(false) or alive(true) and I need to check how many neighbours are alive for a given cell.
private static int checkMyLivingNeighbours(Cell cell,List<Cell> currentcells){
int neighbours = 0;
for (int y = cell.getY() - 1; y <= cell.getY() + 1; y++) {
for (int x = cell.getX() - 1; x <= cell.getX() + 1; x++) {
if(x!=cell.getX() || y!=cell.getY()){
for (Cell nowcell : currentcells) {
if (nowcell.getX() == x && nowcell.getY() == y) {
if (nowcell.getStatus()) {
neighbours++;
}
}
}
}
}
}
return neighbours;
}
I have tried something like this
private static void checkaliveneighbours(Cell cell,List<Cell> generation){
generation.stream().forEach(n->IntStream.range(cell.getY()-1,cell.getY()+1).
forEach(y -> IntStream.range(cell.getX()-1,cell.getX()+1)
.forEach(x->{if(n.getX()==x && n.getY()==y && n.getStatus())System.out.println(n.getDisplaychar());})));;//
}
where I am calling it like such
checkaliveneighbours(generation.get(0),generation);
SO I do get a print for the alive CELL but I actually need the total nr of alive CELLS surrounding the CELL being passed in and not just a print if the cell passed in is alive or not. Therefor the question how to limit number of elements in a stream(just the surrounding cells) responsively(based on the individual cell being passed in).
Here is the cell class
public class Cell {
private int x;
private int y;
private boolean alive;
public Cell(){}
public Cell(String x, String y, boolean alive ) {
this.x = Integer.valueOf(x);
this.y = Integer.valueOf(y);
this.alive = alive;
}
public int getX() {
return x;
}
public void setX(String x) {
this.x = Integer.valueOf(x);
}
public int getY() {
return y;
}
public void setY(String y) {
this.y = Integer.valueOf(y);
}
public boolean getStatus() {
return alive;
}
public void setStatus(boolean status) {
this.alive = status;
}
public char getDisplaychar() {
if(getStatus())
return 'X';
else
return '.';
}
}
If I understand correctly, by "limiting" you mean using Stream.filter() to filter only neighbors. Then you want to sum all living neighbors. I'd begin by defining a method that will return whether a specified cell is a neighboring cell or not:
private static boolean isNeighbor(final Cell cell, final Cell candidate) {
for (int y = cell.getY() - 1; y <= cell.getY() + 1; y++) {
for (int x = cell.getX() - 1; x <= cell.getX() + 1; x++) {
if (x != cell.getX() || y != cell.getY()) {
if (candidate.getX() == x && candidate.getY() == y) {
return true;
}
}
}
}
return false;
}
Then you can easily filter your list and compute the sum like so:
int sum = generation.stream()
.filter(c -> isNeighbor(cell, c))
.mapToInt(c -> c.getStatus() ? 1 : 0)
.sum();
Edit: If you're looking for a pure Java 8 solution for isNeighbor:
private boolean isNeighbor(final Cell cell, final Cell candidate) {
return IntStream.rangeClosed(cell.getX() - 1, cell.getX() + 1)
.anyMatch(x -> IntStream.rangeClosed(cell.getY() - 1, cell.getY() + 1)
.anyMatch(y -> (x != cell.getX() || y != cell.getY()) &&
x == candidate.getX() && y == candidate.getY()));
}

print shapes in java

I want to print this shape big X from collection of small x using recursion
this is my code
private static void shape(PrintWriter output, int times, int k, int times2) {
if(times < 0){
return;
} else{
for (int i =0; i<times; i++){
if (i==times)
output.print("X");
else if(i==k)
output.print("X");
else
output.print(" ");
}
output.println();
shape(output,times-1,k+1,times2);
}
}
but I couldn't print the shape requested
Try this.
static void shape(PrintWriter output, int size, int index) {
if (index >= size)
return;
char[] buffer = new char[size];
Arrays.fill(buffer, ' ');
buffer[index] = buffer[size - index - 1] = 'X';
output.println(new String(buffer));
shape(output, size, index + 1);
}
and
try (PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out))) {
shape(output, 11, 0);
}
Just change
int arr[] = new int[times]
to
int arr[] = new int[times2]
where times2 is the width of a single row.
However a more cleaner way would be:
public class InputTest {
private static void FCITshape(int times, int k,int times2) {
if (times < 0) {
return;
} else {
for (int i = 0; i <= times2; i++) {
if (i == times)
System.out.print("X");
else if (i == k)
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
FCITshape(times - 1, k + 1, times2);
}
}
public static void main(String[] args) {
FCITshape(10, 0, 10);
}
}
Regards.
With recursion
Now just call printX(0, 10);
public static void printX(int x, int l) {
if (x <= l) {
if (x < l / 2) {
for (int i = 0; i < x ; i++) {
System.out.print(" ");
}
} else {
for (int i = 0; i < l - x; i++) {
System.out.print(" ");
}
}
System.out.print("x");
if (x < l / 2) {
for (int j = 0; j < l - x * 2 - 1; j++) {
System.out.print(" ");
}
} else {
for (int j = 0; j < (x * 2 - l) - 1; j++) {
System.out.print(" ");
}
}
if (x != l / 2) {
System.out.print("x");
}
System.out.println();
printX(x + 1, l);
}
}

MergeSort gives StackOverflow error

this is the code for the mergeSort,this gives an stackoverflow error in line 53 and 54(mergeSort(l,m); and mergeSort(m,h);)
Any help will be regarded so valuable,please help me out,i am clueless,Thank you.
package codejam;
public class vector {
static int[] a;
static int[] b;
public static void main(String[] args) {
int[] a1 = {12,33,2,1};
int[] b1 = {12,333,11,1};
mergeSort(0,a1.length);
a1=b1;
mergeSort(0,b1.length);
for (int i = 0; i < a1.length; i++) {
System.out.println(a[i]);
}
}
public static void merge(int l,int m,int h) {
int n1=m-l+1;
int n2 = h-m+1;
int[] left = new int[n1];
int[] right = new int[n2];
int k=l;
for (int i = 0; i < n1 ; i++) {
left[i] = a[k];
k++;
}
for (int i = 0; i < n2; i++) {
right[i] = a[k];
k++;
}
left[n1] = 100000000;
right[n1] = 10000000;
int i=0,j=0;
for ( k =l ; k < h; k++) {
if(left[i]>=right[j])
{
a[k] = right[j];
j++;
}
else
{
a[k] = left[i];
i++;
}
}
}
public static void mergeSort(int l,int h) {
int m =(l+h)/2;
if(l<h)
{
mergeSort(l,m);
mergeSort(m,h);
merge(l,m,h);;
}
}
}
Following is the recursive iterations table of the mergeSort function with argument l=0 and h=4
when the value of l is 0 and value of h is 1 , expression calculate m value which turn out to be 0 but we are checking condition with h which is still 1 so 0<1 become true , recursive calls of this mergeSort function forms a pattern , this pattern doesn't let the function to terminate , stack runs out of memory , cause stackoverflow error.
import java.lang.*;
import java.util.Random;
public class MergeSort {
public static int[] merge_sort(int[] arr, int low, int high ) {
if (low < high) {
int middle = low + (high-low)/2;
merge_sort(arr,low, middle);
merge_sort(arr,middle+1, high);
arr = merge (arr,low,middle, high);
}
return arr;
}
public static int[] merge(int[] arr, int low, int middle, int high) {
int[] helper = new int[arr.length];
for (int i = 0; i <=high; i++){
helper[i] = arr[i];
}
int i = low;
int j = middle+1;
int k = low;
while ( i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
arr[k++] = helper[i++];
} else {
arr[k++] = helper[j++];
}
}
while ( i <= middle){
arr[k++] = helper[i++];
}
while ( j <= high){
arr[k++] = helper[j++];
}
return arr;
}
public static void printArray(int[] B) {
for (int i = 0; i < B.length ; i++) {
System.out.print(B[i] + " ");
}
System.out.println("");
}
public static int[] populateA(int[] B) {
for (int i = 0; i < B.length; i++) {
Random rand = new Random();
B[i] = rand.nextInt(20);
}
return B;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int A[] = new int[10];
A = populateA(A);
System.out.println("Before sorting");
printArray(A);
A = merge_sort(A,0, A.length -1);
System.out.println("Sorted Array");
printArray(A);
}
}

Interview - Oracle

In a game the only scores which can be made are 2,3,4,5,6,7,8 and they can be made any number of times
What are the total number of combinations in which the team can play and the score of 50 can be achieved by the team.
example 8,8,8,8,8,8,2 is valid 8,8,8,8,8,4,4,2 is also valid. etc...
The problem can be solved with dynamic programming, with 2 parameters:
i - the index up to which we have considered
s - the total score.
f(i, s) will contain the total number of ways to achieve score s.
Let score[] be the list of unique positive scores that can be made.
The formulation for the DP solution:
f(0, s) = 1, for all s divisible to score[0]
f(0, s) = 0, otherwise
f(i + 1, s) = Sum [for k = 0 .. floor(s/score[i + 1])] f(i, s - score[i + 1] * k)
This looks like a coin change problem. I wrote some Python code for it a while back.
Edited Solution:
from collections import defaultdict
my_dicto = defaultdict(dict)
def row_analysis(v, my_dicto, coins):
temp = 0
for coin in coins:
if v >= coin:
if v - coin == 0: # changed from if v - coin in (0, 1):
temp += 1
my_dicto[coin][v] = temp
else:
temp += my_dicto[coin][v - coin]
my_dicto[coin][v] = temp
else:
my_dicto[coin][v] = temp
return my_dicto
def get_combs(coins, value):
'''
Returns answer for coin change type problems.
Coins are assumed to be sorted.
Example:
>>> get_combs([1,2,3,5,10,15,20], 50)
2955
'''
dicto = defaultdict(dict)
for v in xrange(value + 1):
dicto = row_analysis(v, dicto, coins)
return dicto[coins[-1]][value]
In your case:
>>> get_combs([2,3,4,5,6,7,8], 50)
3095
It is like visit a 7-branches decision tree.
The code is:
class WinScore{
static final int totalScore=50;
static final int[] list={2,3,4,5,6,7,8};
public static int methodNum=0;
static void visitTree( int achieved , int index){
if (achieved >= totalScore ){
return;
}
for ( int i=index; i< list.length; i++ ){
if ( achieved + list[i] == totalScore ) {
methodNum++;
}else if ( achieved + list[i] < totalScore ){
visitTree( achieved + list[i], i );
}
}
}
public static void main( String[] args ){
visitTree(0, 0);
System.out.println("number of methods are:" + methodNum );
}
}
output:
number of methods are:3095
Just stumbled on this question - here's a c# variation which allows you to explore the different combinations:
static class SlotIterator
{
public static IEnumerable<string> Discover(this int[] set, int maxScore)
{
var st = new Stack<Slot>();
var combinations = 0;
set = set.OrderBy(c => c).ToArray();
st.Push(new Slot(0, 0, set.Length));
while (st.Count > 0)
{
var m = st.Pop();
for (var i = m.Index; i < set.Length; i++)
{
if (m.Counter + set[i] < maxScore)
{
st.Push(m.Clone(m.Counter + set[i], i));
}
else if (m.Counter + set[i] == maxScore)
{
m.SetSlot(i);
yield return m.Slots.PrintSlots(set, ++combinations, maxScore);
}
}
}
}
public static string PrintSlots(this int[] slots, int[] set, int numVariation, int maxScore)
{
var sb = new StringBuilder();
var accumulate = 0;
for (var j = 0; j < slots.Length; j++)
{
if (slots[j] <= 0)
{
continue;
}
var plus = "+";
for (var k = 0; k < slots[j]; k++)
{
accumulate += set[j];
if (accumulate == maxScore) plus = "";
sb.AppendFormat("{0}{1}", set[j], plus);
}
}
sb.AppendFormat("={0} - Variation nr. {1}", accumulate, numVariation);
return sb.ToString();
}
}
public class Slot
{
public Slot(int counter, int index, int countSlots)
{
this.Slots = new int[countSlots];
this.Counter = counter;
this.Index = index;
}
public void SetSlot(int index)
{
this.Slots[index]++;
}
public Slot Clone(int newval, int index)
{
var s = new Slot(newval, index, this.Slots.Length);
this.Slots.CopyTo(s.Slots, 0);
s.SetSlot(index);
return s;
}
public int[] Slots { get; private set; }
public int Counter { get; set; }
public int Index { get; set; }
}
Example:
static void Main(string[] args)
{
using (var sw = new StreamWriter(#"c:\test\comb50.txt"))
{
foreach (var s in new[] { 2, 3, 4, 5, 6, 7, 8 }.Discover(50))
{
sw.WriteLine(s);
}
}
}
Yields 3095 combinations.

Can't use a variable in another method in XNA

I will explain in depth after. So here is my code, we have an Elevation[] variable and each Elevation gets a random number:
public void elevation()
{
for (x = (int)Width - 1; x >= 0; x--)
{
for (y = (int)Width - 1; y >= 0; y--)
{
y = rand.Next((int)MaxElevation); //random number for each y.
Elevation[x] = y; //each Elevation gets a random number.
}
}
}
After this I try to use this random number in the draw method like this:
public void Draw(SpriteBatch spriteBatch)
{
for (x = (int)Width - 1; x >= 0; x--)
{
spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[x], 1, (int)Height), Color.White);
//HERE, I try to acces the random number for each Elevation (y value). But I get 0 everywhere.
}
}
How can I acces this random number?
If I do that:
public void Draw(SpriteBatch spriteBatch)
{
for (x = (int)Width - 1; x >= 0; x--)
{
for (y = (int)Width - 1; y >= 0; y--)
{
y = rand.Next((int)MaxElevation);
spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[y], 1, (int)Height), Color.White);
}
}
}
I will be able to acces the random numbers, but it will update every frame and the random numbers will change. So I need to calculate them once and then use them.
Here is all the code:
namespace procedural_2dterrain
{
class Terrain
{
Texture2D Pixel;
Vector2 Position;
Random rand;
int[] Elevation;
float MaxElevation;
float MinElevation;
float Width;
float Height;
int x;
int y;
public void Initialize( ContentManager Content, float maxElevation, float minElevation, float width, float height, Vector2 position)
{
Pixel = Content.Load<Texture2D>("pixel");
rand = new Random();
Elevation = new int[(int)width];
MaxElevation = maxElevation;
MinElevation = minElevation;
Width = width;
Height = height;
Position = position;
elevation();
}
public void Update()
{
}
public void elevation()
{
for (x = (int)Width - 1; x >= 0; x--)
{
for (y = (int)Width - 1; y >= 0; y--)
{
y = rand.Next((int)MaxElevation);
Elevation[x] = y;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
for (x = (int)Width - 1; x >= 0; x--)
{
spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[x], 1, (int)Height), Color.White);
}
}
}
}
The problem is with your elevation() method. You are using y as your inner loop indexer and also assigning a value to it within the loop. So the loop starts, y is assigned a random value. As it continues the loop, it is decremented and then tested for being >=0. The only time this loop will exit is if y is assigned the random number of 0. So that is why all your Elevation are zero.
I am a little confused as to why you think you need an inner loop. Try:
public void elevation()
{
for (x = (int)Width - 1; x >= 0; x--)
{
Elevation[x] = rand.Next((int)MaxElevation);
}
}

Resources