Convert DEC to IP dart - flutter

I get a int32 : -1407942911 that I need to convert to a ip
I used this function:
_setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip >> 8;
}
return _strData.toString();
}
but I get the ip backwards: 1.127.20.172 instead of 172.20.127.1
I was trying to replicate this java code
public String longToIp(long ip) {
StringBuilder result = new StringBuilder(15);
for (int i = 0; i < 4; i++) {
result.insert(0,Long.toString(ip & 0xff));
if (i < 3) {
sb.insert(0,'.');
}
ip = ip >> 8;
}
return result.toString();
}
Update
I solved the error
static setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip >> 24 &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip << 8;
}
return _strData.toString();
}

You can do something like this:
import 'dart:io';
import 'dart:typed_data';
void main() {
print(getIpFromInt32Value(-1407942911)); // 172.20.127.1
}
String getIpFromInt32Value(int value) => InternetAddress.fromRawAddress(
(ByteData(4)..setInt32(0, value)).buffer.asUint8List())
.address;

This solved the error:
static setIp(int _ip){
var _strData = StringBuffer();
for (int i = 0; i<4; i++){
_strData.write(_ip >> 24 &0xff );
if (i < 3) {
_strData.write(".");
}
_ip = _ip << 8;
}
return _strData.toString();
}

Related

Unity Destroy() doesn't delete script

Noob mistake I was only referencing the parents brain from the child's instead of copying it directly. It's a neural network that can grow in size (or shrink) through genetics. I was going to post it but it doesn't fit on this without me having to type a larger ratio of words to code oh look it works now
public class Animal1 : MonoBehaviour
{
public class Neuron1
{
public int[] children;
public float[] weights;
public float bias;
public float value;
public Neuron1()
{
children = new int[10];
for (int i = 0; i < 10; i++)
{
children[i] = -1;
}
weights = new float[10];
for (int i = 0; i < 10; i++)
{
weights[i] = 1;
}
bias = 0;
value = 0;
}
}
float sightRange = 2;
Vector2 left = new Vector2(-.4f,.6f);
Vector2 right = new Vector2(.4f, .6f);
RaycastHit2D hitLeft;
RaycastHit2D hitForward;
RaycastHit2D hitRight;
public LayerMask animalLayerMask;
[System.NonSerialized]
public int food = 0;
int foodCounter = 0;
int foodForReproduction = 3;
float noFoodCounter = 0;
int lifeWithoutFood = 20;
int maxBrainSize = 100;
[System.NonSerialized]
public Neuron1[] brain1 = new Neuron1[100]; //first three and last three are inputs and outputs and are never mutated
int childrenMaxAmount = 5;
float biasInitRange = 2;
float weightInitRange = 2;
int outputSize = 2;
int inputSize = 3;
GameObject manager;
[System.NonSerialized]
public bool firstGen = false;
[System.NonSerialized]
public GameObject parent1;
[System.NonSerialized]
public bool directCopy = false;
float maxTravelRange = 5;
Color color;
float colorMutationRate = .1f;
public GameObject animal1Prefab1;
bool debugBool = false;
void Start()
{
manager = GameObject.Find("Manager Object");
if (firstGen == true)
{
InitializeBrain(3, 2, 20);
firstGen = false;
transform.GetComponent<SpriteRenderer>().color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
}
else
{
if (parent1.GetComponent<Animal1>().brain1[0].bias == 1234)
{
Debug.Log("parent passing brain after deletion");
}
Mutate(parent1, 5, 1f, .5f);
transform.GetComponent<SpriteRenderer>().color = color;
}
}
void Update()
{
if (brain1[0].bias == 1234)
{
GetComponent<SpriteRenderer>().color = Color.black;
}
//teleportation
if (transform.position.x > maxTravelRange)
{
Vector2 newPosition = new Vector2(-maxTravelRange, transform.position.y);
transform.position = newPosition;
}
if (transform.position.x < -maxTravelRange)
{
Vector2 newPosition = new Vector2(maxTravelRange, transform.position.y);
transform.position = newPosition;
}
if (transform.position.y > maxTravelRange)
{
Vector2 newPosition = new Vector2(transform.position.x, -maxTravelRange);
transform.position = newPosition;
}
if (transform.position.y < -maxTravelRange)
{
Vector2 newPosition = new Vector2(transform.position.x, maxTravelRange);
transform.position = newPosition;
}
//input
hitLeft = Physics2D.Raycast(transform.position, transform.TransformDirection(left), sightRange, ~animalLayerMask); //left
hitForward = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), sightRange, ~animalLayerMask); //forward
hitRight = Physics2D.Raycast(transform.position, transform.TransformDirection(right), sightRange, ~animalLayerMask); //right
if (hitLeft)
{
brain1[0].value = 1;
}
if (hitForward)
{
brain1[1].value = 1;
}
if (hitRight)
{
brain1[2].value = 1;
}
//output
Think();
// one output for speed, another for turning
int rotDir = 1;
if (brain1[maxBrainSize - 1].value < 0)
{
rotDir = -1;
}
Vector3 eulerRotation = new Vector3(0, 0, (45 * rotDir + (transform.rotation.eulerAngles.z % 360)) % 360);
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(eulerRotation), Mathf.Abs(brain1[maxBrainSize - 1].value) * 25 * Time.deltaTime);
if (brain1[maxBrainSize - 2].value > 0) // so they can't go backwards
{
transform.Translate(Vector2.up * (brain1[maxBrainSize - 2].value * .1f) * Time.deltaTime);
}
//reset outputs
brain1[maxBrainSize - 2].value = 0;
brain1[maxBrainSize - 1].value = 0;
// reset inputs
brain1[0].value = 0;
brain1[1].value = 0;
brain1[2].value = 0;
noFoodCounter += Time.deltaTime;
if (food > 0)
{
foodCounter++;
food = 0;
noFoodCounter = 0;
}
if (foodCounter > foodForReproduction)
{
foodCounter = 0;
Reproduce();
}
if (noFoodCounter > lifeWithoutFood/2)
{
foodCounter = 0;
}
if (noFoodCounter > lifeWithoutFood)
{
Destroy(gameObject);
}
}
void InitializeBrain(int inputs, int outputs, int sizeExcludingInputsAndOutputs)
{
for (int i = 0; i < sizeExcludingInputsAndOutputs + inputs; i++)
{
brain1[i] = new Neuron1();
}
for (int i = maxBrainSize - outputs; i < maxBrainSize; i++) // outputs
{
brain1[i] = new Neuron1();
}
// all neurons in between the inputs and outputs
for (int i = inputs; i < sizeExcludingInputsAndOutputs + inputs; i++)
{
brain1[i].bias = Random.Range(-biasInitRange, biasInitRange);
for (short j = 0; j < childrenMaxAmount -1; j++) // -1 so there is always at least one free space for a child
{
int rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains) // making sure none are children of themselves, and that it doesn't already have this child
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[i].children[h] == rnd1) // if it already has this child
{
alreadyContains = true;
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
while (rnd1 == i) // and its not itself
{
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
}
break;
}
}
errorCounter++;
if (errorCounter > 100) // so we don't get stuck in small network sizes
{
goto outside2;
}
}
brain1[i].children[j] = rnd1;
brain1[i].weights[j] = Random.Range(-weightInitRange, weightInitRange);
if (Random.Range(1, 10) > 8)
{
break; // so not every neuron has the same amount of children
}
}
outside2:
{
}
}
// assign children of inputs
for (int i = 0; i < inputs; i++)
{
for (int j = 0; j < childrenMaxAmount; j++) // assigning all max children (sometimes) to inputs, their amounts of children will never change
{
int rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains)
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[i].children[h] == rnd1)
{
alreadyContains = true;
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
}
}
errorCounter++;
if (errorCounter > 1000) // so we don't get stuck in small network sizes
{
goto outside1;
}
}
brain1[i].children[j] = rnd1;
//brain1[i].weights[j] = 100; // input weight
}
outside1:
{
}
}
RemoveDeadNeurons();
// assign parents of outputs
int brainEnd = maxBrainSize - outputs;
for (int i = brainEnd; i < maxBrainSize; i++)
{
for (short j = 0; j < childrenMaxAmount; j++) // same amount of parents as inputs have children
{
int rnd1 = Random.Range(inputs, brainEnd);
while (brain1[rnd1] == null)
{
rnd1 = Random.Range(inputs, brainEnd);
}
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains) //making sure we dont already have this parent
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[rnd1].children[h] == i)
{
alreadyContains = true;
rnd1 = Random.Range(inputs, brainEnd);
while (brain1[rnd1] == null)
{
rnd1 = Random.Range(inputs, brainEnd);
}
}
}
errorCounter++;
if (errorCounter > 1000) // so we don't get stuck
{
goto outside3;
}
}
for (int h = 0; h < childrenMaxAmount; h++) //adding to next available child space of the parent
{
if (brain1[rnd1].children[h] == -1)
{
brain1[rnd1].children[h] = i;
brain1[rnd1].weights[h] = Random.Range(-weightInitRange, weightInitRange);
break;
}
}
}
outside3:
{
}
}
}
void Think()
{
int[] activatedChildrenIndexes = new int[500];
int[] workingArray = new int[500];
int workingArrayCounter = 0;
short layerCounter = 0;
for (int i = 0; i < 500; i++)
{
activatedChildrenIndexes[i] = -1;
}
//initializing inputs as first activated children layer to be calculated
activatedChildrenIndexes[0] = 0;
activatedChildrenIndexes[1] = 1;
activatedChildrenIndexes[2] = 2;
int thoughtDepth = 6; //keep this as low as possible, will change to make it a percent of the amount of neurons that already exist
for (int x = 0; x < thoughtDepth; x++)
{
for (int i = 0; i < 500; i++) // cycle through activated children and add their activated children to a list
{
int currentNodeIndex = activatedChildrenIndexes[i];
if (currentNodeIndex == -1)
{
layerCounter++;
break;
}
//activation function
if (brain1[currentNodeIndex].value <= 0)
{
brain1[currentNodeIndex].value = 0;
}
else
{
brain1[currentNodeIndex].value = 1;
}
for (int j = 0; j < childrenMaxAmount; j++)
{
if (brain1[currentNodeIndex].children[j] == -1)
{
break;
}
brain1[brain1[currentNodeIndex].children[j]].value
+= (brain1[currentNodeIndex].value * brain1[currentNodeIndex].weights[j]) + brain1[currentNodeIndex].bias;
bool activatedChildIsInNextLayer = false;
for (int h = 0; h < 500; h++)
{
if (brain1[currentNodeIndex].children[j] == activatedChildrenIndexes[h])
{
activatedChildIsInNextLayer = true;
}
}
if (brain1[brain1[currentNodeIndex].children[j]].value > 0
|| layerCounter == 0
|| brain1[currentNodeIndex].children[j] > maxBrainSize - outputSize)
{
if (!activatedChildIsInNextLayer)
{
workingArray[workingArrayCounter] = brain1[currentNodeIndex].children[j];
if (workingArrayCounter < 499)//to prevent out of bounds indexing
{
workingArrayCounter++;
}
}
}
if (brain1[brain1[currentNodeIndex].children[j]].value < 0 && brain1[currentNodeIndex].children[j] < maxBrainSize - outputSize)
{
brain1[brain1[currentNodeIndex].children[j]].value = 0; //resetting negative nodes that didn't get added to next layer
}
}
brain1[currentNodeIndex].value = 0; // resetting value after passing to children
}
for (int i = workingArrayCounter; i < 500; i++)
{
workingArray[i] = -1;
}
workingArrayCounter = 0;
for (int i = 0; i < 500; i++)
{
activatedChildrenIndexes[i] = workingArray[i];
}
}
}
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
for (int i = 0; i < maxBrainSize; i++) // initialized to its parent's brain
{
if (parent.GetComponent<Animal1>().brain1[i] != null)
{
brain1[i] = new Neuron1();
brain1[i].bias = parent.GetComponent<Animal1>().brain1[i].bias;
for (int j = 0; j < childrenMaxAmount; j++)
{
brain1[i].children[j] = parent.GetComponent<Animal1>().brain1[i].children[j];
brain1[i].weights[j] = parent.GetComponent<Animal1>().brain1[i].weights[j];
}
}
}
for (int i = inputSize; i < maxBrainSize - outputSize; i++)
{
if (brain1[i] != null)
{
if (Random.Range(0, 100) < mutationRate) // it will be mutated
{
switch (Random.Range(1, 5))
{
case 1: //change one of its weights
int weightCounter = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its weights
{
if (brain1[i].children[k] != -1)
{
weightCounter++;
}
else
{
break;
}
}
brain1[i].weights[Random.Range(0, weightCounter)] += Random.Range(-weightsMutate, weightsMutate);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 2: //change its bias
brain1[i].bias += Random.Range(-biasMutate, biasMutate);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 3: //break a connection/ remove neuron
int childrenCounter = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[i].children[k] != -1)
{
childrenCounter++;
}
else
{
break;
}
}
int rndChild = Random.Range(0, childrenCounter);
for (int s = rndChild; s < childrenMaxAmount - 1; s++) // shift children list down starting from rndChild and to the second to last element
{
brain1[i].children[s] = brain1[i].children[s + 1];
brain1[i].weights[s] = brain1[i].weights[s + 1];
}
brain1[i].children[childrenMaxAmount - 1] = -1; // removing the last child after shifting the list down one
brain1[i].weights[childrenMaxAmount - 1] = 0;
RemoveDeadNeurons();
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 4: //add a new child if possible
int childrenCounter2 = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[i].children[k] != -1)
{
childrenCounter2++;
}
else
{
break;
}
}
if (childrenCounter2 < childrenMaxAmount) // if we have room for another child
{
int newChild = Random.Range(inputSize, maxBrainSize);
while (brain1[newChild] == null)
{
newChild = Random.Range(inputSize, maxBrainSize);
}
brain1[i].children[childrenCounter2] = newChild;
brain1[i].weights[childrenCounter2] = Random.Range(-weightInitRange, weightInitRange);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
}
break;
}
}
}
}
if (Random.Range(0, 100) < 10) // create a new neuron if space is available for one
{
for (int i = inputSize; i < maxBrainSize - outputSize; i++)
{
if (brain1[i] == null) // the first available neuron
{
brain1[i] = new Neuron1();
int rndParent = Random.Range(0, maxBrainSize - outputSize);
int childrenCounter3 = 0;
if (brain1[rndParent] != null)
{
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[rndParent].children[k] != -1)
{
childrenCounter3++;
}
else
{
break;
}
}
}
while (brain1[rndParent] == null || childrenCounter3 == childrenMaxAmount) // making sure it is both an existing neuron and that it has room for another child
{
childrenCounter3 = 0;
rndParent = Random.Range(0, maxBrainSize - outputSize);
if (brain1[rndParent] != null)
{
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[rndParent].children[k] != -1)
{
childrenCounter3++;
}
else
{
break;
}
}
}
}
brain1[rndParent].children[childrenCounter3] = i; //giving the neuron a parent
brain1[rndParent].weights[childrenCounter3] = Random.Range(-weightInitRange, weightInitRange);
int rndChild = Random.Range(inputSize, maxBrainSize);
while(brain1[rndChild] == null)
{
rndChild = Random.Range(inputSize, maxBrainSize);
}
brain1[i].children[0] = rndChild; // giving the new neuron a child, a weight, and its bias
brain1[i].weights[0] = Random.Range(-weightInitRange, weightInitRange);
brain1[i].bias = Random.Range(-biasInitRange, biasInitRange);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
}
}
}
}
void RemoveDeadNeurons()
{
bool allGood = false;
while (!allGood)
{
for (int i = inputSize; i < maxBrainSize - outputSize; i++) // for every hidden layer neuron
{
if (brain1[i] != null) // if it's a neuron
{
if (brain1[i].children[0] == -1) // if it has no children
{
brain1[i] = null; // deleting neuron
for (int h = 0; h < maxBrainSize - outputSize; h++) //remove from other neurons children list, including from the input layer
{
if (brain1[h] != null)
{
for (int g = 0; g < childrenMaxAmount; g++)
{
if (brain1[h].children[g] == i) // if brain[h] has the removed neuron as a child
{
for (int s = g; s < childrenMaxAmount - 1; s++) // shift children list down
{
brain1[h].children[s] = brain1[h].children[s + 1];
brain1[h].weights[s] = brain1[h].weights[s + 1];
}
brain1[h].children[childrenMaxAmount - 1] = -1; // removing the last child in the list after shifting it down one
brain1[h].weights[childrenMaxAmount - 1] = 0;
}
}
}
}
goto outsideRDNLoop; // break out of for loop and recheck the brain
}
bool parentless = true;
for (int h = 0; h < maxBrainSize - outputSize; h++) // check if it is parentless
{
if (brain1[h] != null)
{
for (int g = 0; g < childrenMaxAmount; g++)
{
if (brain1[h].children[g] == i) // if it is a child of brain[h]
{
parentless = false;
}
}
}
}
if (parentless)
{
brain1[i] = null; //deleting neuron
goto outsideRDNLoop;
}
}
if (i == (maxBrainSize - outputSize) - 1) // if we reached the end of the for loop and this line, we know the brain was allGood
{
allGood = true;
}
}
outsideRDNLoop:
{
}
}
}
void Reproduce()
{
GameObject offspring = Instantiate(animal1Prefab1, new Vector2(transform.position.x + 1, transform.position.y + 1), Quaternion.identity);
offspring.GetComponent<Animal1>().parent1 = gameObject;
offspring.name = "animal1";
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, transform.TransformDirection(left) * sightRange);
Gizmos.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * sightRange);
Gizmos.DrawRay(transform.position, transform.TransformDirection(right) * sightRange);
}
}
I've not run your code, just looked at it, but this looks suspicious if you are having problems with the contents of brain1 being overwritten elsewhere:
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
// This line here is suspicious:
brain1 = parent.GetComponent<Animal1>().brain1; // initialized to its parent's brain
What you are doing here is replacing the reference to the child's brain with the parent's - so if you are starting with just one parent initially, every single entity will be sharing the same brain.
I think perhaps you meant to deep copy the contents from parent's brain into the child's brain? What your assignment here is doing is just taking the reference to the parent's brain and using it as the child brain as well.
Example Deep copy:
Updated Neuron1 class:
public class Neuron1
{
public int[] children;
public float[] weights;
public float bias;
public float value;
public Neuron1()
{
children = new int[10];
for (int i = 0; i < 10; i++)
{
children[i] = -1; // to stop looping when reaching -1
}
weights = new float[10];
for (int i = 0; i < 10; i++)
{
weights[i] = 1;
}
bias = 0;
value = 0;
}
// Added clone function:
public Neuron1 Clone()
{
Neuron1 clone = new Neuron1();
for (int i = 0; i < clone.children.Length; i++)
{
clone.children[i] = this.children[i];
}
for (int i = 0; i < clone.weights.Length; i++)
{
clone.weights[i] = this.weights[i];
}
clone.bias = this.bias;
clone.value = this.value;
return clone;
}
}
Updated start of Mutate function.
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
Neuron1[] parentBrain = parent.GetComponent<Animal1>().brain1; // initialized to its parent's brain
for (int i = 0; i < brain1.Length; ++i)
{
brain1[i] = parentBrain[i].Clone();
}
Well, I have a demo scene here. In it I created an empty game object. It has a script attached to it (CSharp.cs), like this:
In my Update method I wrote
And as soon as I start the game, the game object including the script is deleted.
But if I replace transform.gameObject wit just this then only the script disappears and the game object remains.
DestoryImmediate() is not recommended to be used, instead use Destory()
Destroy() will set the object to null at the end of the frame and whereas DestroyImmediate() function immediately set object reference to null.
DestoryImmediate can also delete prefabs/scenes/art in your project outside of playmode which is another reason you should not use it.

Maximum value of range of values in array (C++)

The array ampVal has 25600 integers inside it. I need to find the maximum value of each set of 1024 values in the array and store it in another array. However I'm not getting this part to work it only gives 21 values and a random number '1348410436'. ampVal is a dynamic array.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int main() {
ifstream miniProject;
int n = 0;
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
cout << "File not found" << endl;
}
else {
cout<<"File Located ! :D \nCounting Lines in file..." << endl;
while (miniProject) {
string lines;
getline(miniProject, lines);
n++;
}
cout << "Number of lines in file are: " << n << endl;
miniProject.close();
}
int *frNum = new int[n];
int *bitNum = new int[n];
int *ampVal = new int[n];
for (int i = 0; i < n;i++){
frNum[i] = 0;
bitNum[i] = 0;
ampVal[i] = 0;
}
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
cout << "File not found" << endl;
}
else {
int i = 0;
string frameNumber, bitNumber, amplitudeValue;
while (miniProject) {
(miniProject >> frameNumber >> bitNumber >> amplitudeValue);
stringstream(frameNumber) >> frNum[i];
stringstream(bitNumber) >> bitNum[i];
stringstream(amplitudeValue) >> ampVal[i];
i++;
}
}
miniProject.close();
int frameGroupStart = 0;
int frameGroupEnd = 1024;
int maxAmpVal = 0;
while (frameGroupEnd != 25600) {
for (int i = frameGroupStart; i < frameGroupEnd; i++) {
if (ampVal[i] >maxAmpVal) {
maxAmpVal = ampVal[i];
cout << maxAmpVal << endl;
}
}
frameGroupStart = frameGroupStart + 1024;
frameGroupEnd = frameGroupEnd + 1024;
}
getchar();
return 0;
}
I used an alternate approach and this gets the job done:
int bitGroupStart = 0;
int bitGroupEnd = 1024;
int arrayOfMaxAmpVal[25];
int frameNumMaxVal[25];
int maxAmpVal = 0;
for (int i = 0; i < 25; i++) {
for (int j = bitGroupStart; j < bitGroupEnd; j++) {
if (ampVal[j] > maxAmpVal) {
maxAmpVal = ampVal[j];
}
}
bitGroupStart = bitGroupStart + 1024;
bitGroupEnd = bitGroupEnd + 1024;
arrayOfMaxAmpVal[i] = maxAmpVal;
frameNumMaxVal[i] = i;
maxAmpVal = 0;
}

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");
}

Bingo Game, class interface errors?

Can anyone tell me why I am getting these errors? And if so, how do i fix them?
Bingo.java:176: ']' expected
private static void makeCard(int[][] card, int[picks])
^
Bingo.java:176: ')' expected
private static void makeCard(int[][] card, int[picks])
^
Bingo.java:176: illegal start of type
private static void makeCard(int[][] card, int[picks])
^
Bingo.java:176: <identifier> expected
private static void makeCard(int[][] card, int[picks])
^
Bingo.java:177: ';' expected
{
^
Bingo.java:178: illegal start of type
System.out.println("Current Number Picks: \n");
^
Bingo.java:178: ';' expected
System.out.println("Current Number Picks: \n");
^
Bingo.java:178: invalid method declaration; return type required
System.out.println("Current Number Picks: \n");
^
Bingo.java:178: illegal start of type
System.out.println("Current Number Picks: \n");
^
Bingo.java:181: illegal start of type
for (int i=0; i<count; i++){
^
Bingo.java:181: ')' expected
for (int i=0; i<count; i++){
^
Bingo.java:181: illegal start of type
for (int i=0; i<count; i++){
^
Bingo.java:181: <identifier> expected
for (int i=0; i<count; i++){
^
Bingo.java:181: ';' expected
for (int i=0; i<count; i++){
^
Bingo.java:181: > expected
for (int i=0; i<count; i++){
^
Bingo.java:181: '(' expected
for (int i=0; i<count; i++){
^
Bingo.java:189: class, interface, or enum expected
private static void announceWin(int winFound, int numPicks)
^
Bingo.java:192: class, interface, or enum expected
}
^
Bingo.java:196: class, interface, or enum expected
for (int i = 0; i < numPicks; i++){
^
Bingo.java:196: class, interface, or enum expected
for (int i = 0; i < numPicks; i++){
^
Bingo.java:198: class, interface, or enum expected
return true;}
^
Bingo.java:202: class, interface, or enum expected
}
^
22 errors
Here is the code:
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Bingo
{
public static final int ROWS = 5;
public static final int COLS = 5;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int HORIZONTAL = 3;
public static int winFound;
public static int currPick = 0;
public static int randomPick;
public static int WinFound;
public static void main(String[] args)
{
int Totcards;
int[][] card = new int[ROWS][COLS];
fillCard (card);
printCard(card);
playGame(card);
printCard(card);
}
private static void fillCard (int[][] card)
{
// FileReader fileIn = new FileReader("Bingo.in");
// Bufferreader in = new Bufferreader(fileIn);
try {
Scanner scan = new Scanner(new File("bingo.in"));
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
card[i][j] = scan.nextInt();
}
}
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
private static void printCard (int[][] card)
{
System.out.println("\n\tYOUR BINGO CARD : ");
System.out.println("\n\tB I N G O");
System.out.println("\t----------------------");
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
System.out.print("\t" + card[i][j]);
}
System.out.print("\n");
}
}
private static void playGame (int[][] card)
{
int numPicks = 0;
while (true)
{
markCard (card); // Generate a random num & zero-it out
winFound = checkForWin(card); // Look for zero sums
numPicks++;
if (winFound != 0)
{
announceWin (winFound, numPicks);
return;
}
}
}
private static void markCard (int[][] card)
{
int randomPick = (int) (Math.random() * 74) + 1;
for (int j = 0; j < ROWS; j++){
for (int k = 0; k < COLS; k++){
if (card[j][k]==randomPick)
card[j][k] = 0;}
System.out.print(" " + randomPick);
}
}
private static int checkForWin(int[][] card)
{
int sum=0;
for (int i = 0; i < ROWS; i++)
{
sum = 0;
for (int j = 0; j < COLS; j++)
sum += card[i][j];
if (sum == 0)
return HORIZONTAL;
}
for (int j = 0; j < COLS; j++)
{
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][j];
if (sum == 0)
return VERTICAL;
}
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][ROWS-i-1];
if (sum == 0)
return DIAGONAL;
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][i];
if (sum == 0)
return DIAGONAL;
return WinFound;
}
private static void makeCard(int[][] card, int[picks])
{
System.out.println("Current Number Picks: \n");
int count = 100;
int currPick = 0;
for (int i=0; i<count; i++){
currPick = (int)(Math.random() * 74) + 1;
System.out.print(" " + currPick + "\n");
picks[i] = currPick;
System.out.print("i: " + i);
}
}
private static void announceWin(int winFound, int numPicks)
{
System.out.println("winFound: " + winFound + "numpicks: " + numPicks);
}
private static boolean duplicate (int currPick, int[picks], int numPicks)
{
for (int i = 0; i < numPicks; i++){
if (picks[i] == currPick){
return true;}
}
return false;
}
}
You're accepting an int array parameter incorrectly.
You have int [picks] where it should be int[] picks
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Bingo
{
public static final int ROWS = 5;
public static final int COLS = 5;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int HORIZONTAL = 3;
public static int winFound;
public static int currPick = 0;
public static int randomPick;
public static int WinFound;
public static void main(String[] args)
{
int Totcards;
int[][] card = new int[ROWS][COLS];
fillCard (card);
printCard(card);
playGame(card);
printCard(card);
}
private static void fillCard (int[][] card)
{
// FileReader fileIn = new FileReader("Bingo.in");
// Bufferreader in = new Bufferreader(fileIn);
try {
Scanner scan = new Scanner(new File("bingo.in"));
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
card[i][j] = scan.nextInt();
}
}
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
private static void printCard (int[][] card)
{
System.out.println("\n\tYOUR BINGO CARD : ");
System.out.println("\n\tB I N G O");
System.out.println("\t----------------------");
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
System.out.print("\t" + card[i][j]);
}
System.out.print("\n");
}
}
private static void playGame (int[][] card)
{
int numPicks = 0;
while (true)
{
markCard (card); // Generate a random num & zero-it out
winFound = checkForWin(card); // Look for zero sums
numPicks++;
if (winFound != 0)
{
announceWin (winFound, numPicks);
return;
}
}
}
private static void markCard (int[][] card)
{
int randomPick = (int) (Math.random() * 74) + 1;
for (int j = 0; j < ROWS; j++){
for (int k = 0; k < COLS; k++){
if (card[j][k]==randomPick)
card[j][k] = 0;}
System.out.print(" " + randomPick);
}
}
private static int checkForWin(int[][] card)
{
int sum=0;
for (int i = 0; i < ROWS; i++)
{
sum = 0;
for (int j = 0; j < COLS; j++)
sum += card[i][j];
if (sum == 0)
return HORIZONTAL;
}
for (int j = 0; j < COLS; j++)
{
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][j];
if (sum == 0)
return VERTICAL;
}
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][ROWS-i-1];
if (sum == 0)
return DIAGONAL;
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][i];
if (sum == 0)
return DIAGONAL;
return WinFound;
}
private static void makeCard(int[][] card, int[] picks)
{
System.out.println("Current Number Picks: \n");
int count = 100;
int currPick = 0;
for (int i=0; i<count; i++){
currPick = (int)(Math.random() * 74) + 1;
System.out.print(" " + currPick + "\n");
picks[i] = currPick;
System.out.print("i: " + i);
}
}
private static void announceWin(int winFound, int numPicks)
{
System.out.println("winFound: " + winFound + "numpicks: " + numPicks);
}
private static boolean duplicate (int currPick, int[] picks, int numPicks)
{
for (int i = 0; i < numPicks; i++){
if (picks[i] == currPick){
return true;}
}
return false;
}
}
Compiles for me

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type