Algo Issue - Find a group of item in a list - arrays

Here is what I'm trying to do :
I have 2 lists.
List 1 : 00F0001,00F0002,00F0003,00F0004,00F0005,00F0006,00F0007,00F0008,00F0009,00F0010
List 2 : 00F0006,00F0007,00F0008 (this list is generate by the 1st item($debut) and the last one($fin))
What i want to do is :
return me true if the "List 2" is in the "List 1", just that.
So I tried with 2 for but I get blocked :/
My code :
$id = substr($debut,0,4);
echo '</br>id : '.$id; /* = 00F0*/
$Start = substr($debut,4,25);
$End = substr($fin,4,25);
$range = $End - $Start +1;
echo '</br>Range : '.$range; /* = 3 with the example I gave*/
for ($i = 0;$i < $range;$i++){
$indice2 = $Start + $i;
$Num_Serie = str_pad($indice2, 4, '0', STR_PAD_LEFT);
$Num_Serie_Final[$i] = $id.''.$Num_Serie;
}
$ArrayNS = $Num_Serie_Final;
$i_W = 0;
while(($produit = $reponse->fetch())AND($check3 == "false")){
$ArrayProduit[$i_W] = $produit[1];
$i_W++;
}
for ($i2 = 0; $i2 < $i_W; $i2++){
for ($i3 = 0; $i3 < $range; $i3++){
if ($ArrayNS[$i2] == $ArrayProduit[$i3]){
.... ???? .....
}
}
}
The 1st "for" is to build my "List 2".
The "while" loop is to generate my "List 1"
Then i did a double "for" loop but its here where I lock :/
EDIT
I tried something for the one interested :
for ($i3 = 0; $i3 < $range; $i3++){
for ($i2 = 0; $i2 < $i_W; $i2++){
if ($ArrayNS[$i3] == $ArrayProduit[$i2]){
for ($indice=0; $indice < $range; $indice++){
if ($ArrayNS[$indice] == $ArrayProduit[$i2+$indice]){
$ok = true;
echo '$ArrayNS[$indice] : '.$ArrayNS[$indice].' == $ArrayProduit[$i2+$indice] : '.$ArrayProduit[$i2+$indice].'</br>';
}
else {
$ok = false;
$id_erreur = $ArrayNS[$indice];
echo 'Fail with : '.$ArrayNS[$indice].' !== '.$ArrayProduit[$i2+$indice].'</br>';
}
}
if ($ok) {
echo 'Success !!!';
return ($ok);
}
else {
echo 'Fail !!!';
return ($id_erreur);
}
}
}
}
Probably not the best way to do it but it works ^^

I chose js for console testability, but the algorithm is the same in php.
This one returns an index, but you just have to check if your index is different from -1 to tell if it has been found or not.
The idea is to loop through each element of the haystack (l1 here) and if the current element matches the first element of our needle (l2) then we start to loop from the current haystack index (i) to the end of our needle index (i + j), but if any of these elements doesn't match (at the first occurrence) we skip to the next value of the haystack (l1) and try again. If we did not fail (failedMatch flag) then return the index of the subsequence (l2 in l1 start position).
If the subsequence doesn't appear in the haystack we return -1 by convention.
This is a left to right approach so it will only match the first occurrence of the subsequence, and if it appears more than once, you won't know.
var l1 = [1,2,3,3,4,5,6],
l2 = [3,4,5];
function subsequenceIndex(l1 /* haystack */, l2 /* needle */) {
var startIndex = -1,
failedMatch;
for (var i = 0; i < l1.length; i++) {
failedMatch = false;
if (l1[i] === l2[0]) {
for (var j = 1; j < l2.length; j++) {
// check first that l1[i + j] is set
if (l1[i + j] !== undefined && l2[j] !== l1[i + j]) {
failedMatch = true;
break;
}
}
if (!failedMatch) {
startIndex = i;
}
}
if (startIndex !== -1) {
return startIndex;
}
}
return startIndex;
}

Related

2 object of same type returns true when != checked

I am using model.GetType().GetProperties() with foreach to compare properties of 2 object of same class.
like this
foreach (var item in kayit.GetType().GetProperties())
{
var g = item.GetValue(plu);
var b = item.GetValue(kayit);
if (g is string && b is string&& g!=b)
{
a += item.Name + "*";
}
else if (g is DateTime&& b is DateTime&& g!=b)
{
a += item.Name + "*";
}
}
But the problem is even if they have the same value g!=b returns a true all the time. I have used a break point to prove this and they are literally same thing. Actually I am taking the value putting it in textbox then creating another class after button click and comaring to see the changed properties. So even if I don't change anything it doesn't read the mas equals. Can someone help me about this please?
more info:
I get the plu from database and populate my control with it:
txtorder.Text = plu.OrderNo;
dtporder.Value = nulldate(plu.OrderDate);
dtp1fit.Value = nulldate(plu.FirstFitDate);
dtp1yorum.Value = nulldate(plu.FirstCritDate);
dtp2fit.Value = nulldate(plu.SecondFitDate);
dtp2yorum.Value = nulldate(plu.SecondCritDate);
dtpsizeset.Value = nulldate(plu.SizeSetDate);
dtpsizesetok.Value = nulldate(plu.SizeSetOkDate);
dtpkumasplan.Value = nulldate(plu.FabricOrderByPlan);
txtTedarikci.Text = plu.Fabric_Supplier;
dtpkumasFP.Value = nulldate(plu.FabricOrderByFD);
dtpfabarrive.Value = nulldate(plu.FabricArrive);
dtpbulk.Value = nulldate(plu.BulkFabricDate);
dtpbulkok.Value = nulldate(plu.BulkConfirmDate);
dtpaccessory.Value = nulldate(plu.AccessoriesDate);
dtpaccessoryarrive.Value = nulldate(plu.AccessoriesArriveDate);
dtpcutok.Value = nulldate(plu.ProductionStartConfirmation);
dtpcutstart.Value = nulldate(plu.ProductionStart);
dtpshipmentdate.Value = nulldate(plu.ShipmentDate);
dtpshipmentsample.Value = nulldate(plu.ShipmentSampleDate);
dtpshippedon.Value = nulldate(plu.Shippedon);
nulldate is just a method where I change null values to my default value.
And this is what I do after button click:
var kayit = new uretim();
kayit.OrderNo = txtorder.Text.ToUpper();
kayit.OrderDate = vdat(dtporder.Value);
kayit.FirstFitDate = vdat(dtp1fit.Value);
kayit.FirstCritDate = vdat(dtp1yorum.Value);
kayit.SecondFitDate = vdat(dtp2fit.Value);
kayit.SecondCritDate = vdat(dtp2yorum.Value);
kayit.SizeSetDate = vdat(dtpsizeset.Value);
kayit.SizeSetOkDate = vdat(dtpsizesetok.Value);
kayit.FabricOrderByPlan = vdat(dtpkumasplan.Value);
kayit.Fabric_Supplier = txtTedarikci.Text;
kayit.FabricOrderByFD = vdat(dtpkumasFP.Value);
kayit.FabricArrive = vdat(dtpfabarrive.Value);
kayit.BulkFabricDate = vdat(dtpbulk.Value);
kayit.BulkConfirmDate = vdat(dtpbulkok.Value);
kayit.AccessoriesDate = vdat(dtpaccessory.Value);
kayit.AccessoriesArriveDate = vdat(dtpaccessoryarrive.Value);
kayit.ProductionStartConfirmation = vdat(dtpcutok.Value);
kayit.ProductionStart = vdat(dtpcutstart.Value);
kayit.ShipmentDate = vdat(dtpshipmentdate.Value);
kayit.ShipmentSampleDate = vdat(dtpshipmentsample.Value);
kayit.Shippedon = vdat(dtpshippedon.Value);
kayit.Status = true;
kayit.WrittenDate = DateTime.Now;
kayit.GuidKey = plu.GuidKey != null ? plu.GuidKey : Guid.NewGuid().ToString("N");
I have proven by breakpoint that values are actually same. But the != check retruns a true.
When you are doing
g != b
compiler doesn't know that these objects are strings to compare so it compares their references. You can do:
g.Equals(b) //be carefull if one of them is null
or
g.ToString() != b.ToString()
EDIT
You can compare them after you check the type:
if (g is string && b is string)
{
if( g.ToString() != b.ToString() ){
}
}

BeforeSave not being called during seeding

Is beforeSave() supposed to be called during seeding?
The beforeSave() method in my model table currently gets called when I go through the app (in both edit and add), as intended fields get updated after the form submission.
However, when I seed the database after truncating the table, these same fields remain at their default value.
Seed:
public function run()
{
$data = [
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-01', 'game_type_id'=>2, 'user_pt'=>1, 'opponent'=>'Vancouver', 'opponent_pt'=>2, 'is_decision'=>1, 'mins'=>60, 'ga'=>2, 'sog'=>24],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-02', 'game_type_id'=>2, 'user_pt'=>2, 'opponent'=>'Vancouver', 'opponent_pt'=>1, 'is_decision'=>1, 'mins'=>59, 'secs'=>45, 'ga'=>1, 'sog'=>27],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-03', 'game_type_id'=>2, 'user_pt'=>4, 'opponent'=>'Vancouver', 'opponent_pt'=>1, 'is_decision'=>1, 'mins'=>60, 'ga'=>1, 'sog'=>19],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-04', 'game_type_id'=>2, 'user_pt'=>5, 'opponent'=>'Edmonton', 'opponent_pt'=>2, 'is_decision'=>1, 'mins'=>58, 'secs'=>24, 'ga'=>1, 'sog'=>19],
['season_id'=>1, 'league_id'=>1, 'game_date'=>'2017-01-05', 'game_type_id'=>2, 'user_pt'=>3, 'opponent'=>'Calgary', 'opponent_pt'=>4, 'is_decision'=>1, 'mins'=>59, 'secs'=>10, 'ga'=>1, 'sog'=>19],
];
$table = $this->table('games');
$table->insert($data)->save();
}
BeforeSave
// In a table or behavior class
public function beforeSave($event, $entity, $options)
{
// calculate record if part of decision
if (isset($entity->is_decision) && $entity->is_decision == 1){
//reset
$entity->l = 0;
$entity->w = 0;
$entity->t = 0;
$entity->otl = 0;
$entity->is_shutout = 0;
//calculate result of game
if($entity->is_overtime == 0){
//loss
if($entity->opponent_pt > $entity->user_pt)
$entity->l = 1;
elseif($entity->opponent_pt < $entity->user_pt)
$entity->w = 1;
//tie
elseif($entity->opponent_pt = $entity->user_pt)
$entity->t = 1;
}
else{
//ot loss
if($entity->opponent_pt > $entity->user_pt)
$entity->otl = 1;
}
//calculate shutout
if($entity->opponent_pt == 0)
$entity->is_shutout = 1;
$entity->abs_game_time = 0;
//calculate absolute game time
if(isset($entity->mins) && is_numeric($entity->mins) && $entity->mins > 0)
{
if(isset($entity->secs) && is_numeric($entity->secs) && $entity->secs > 0){
$entity->abs_game_time = ($entity->mins * 60 + $entity->secs)/60;
}
else
$entity->abs_game_time = $entity->mins;
}
}
}
Edit #1
Updated code snippets, still no go
This won't work because seeds don't use the Cake ORM.
use Phinx\Db\Table as BaseTable;
class Table extends BaseTable { /*...*/ }

how to check if a JSONArray is empty in java?

I am working on an android app that get json content of a webservice called "WebUntis". The Json content i am getting looks like:
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"kl":[{"id":71}],
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
As you can see in the result-array there are also other arrays like "kl", "su" and "ro"
I am getting the content of these array and then i store them in an arraylist.
But when one of these array is empty, like;
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"**kl":[]**,
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
I am always getting the error IndexOutOfRangeException,
but I am always telling it that it should not take the empty arrays, this is what I have tried:
JSONObject jsonResult = new JSONObject(s);
// Get the result object
JSONArray arr = jsonResult.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
anfangStunde[i] = c.getString("startTime");
endeStunde[i] = c.getString("endTime");
// get the jsonarrays (kl, su, ro)
kl = c.getJSONArray("kl");
su = c.getJSONArray("su");
ro = c.getJSONArray("ro");
// check if kl is not null
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
if (klassenID[i] != null) {
klasse = webuntis.klassenMap.get(klassenID[i]);
Log.d("ID und Klasse=", "" + klassenID[i] + ";" + klasse);
}
// get th ids
fachID[i] = su.getJSONObject(0).getString("id");
if (fachID[i] != null) {
fach = webuntis.faecherMap.get(fachID[i]);
Log.d("ID und Fach=", "" + fachID[i] + ";" + fach);
}
// "Start;Ende;Klasse;Fach;Raum" store in arraylist
webuntis.stundenPlan.add(anfangStunde[i] + ";" + endeStunde[i] + ";" + klasse + ";" + fach);
// Write Data into a file for offline use:
}
Can anyone help me ?
If the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.
Instead you can check the length(), e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can also use isEmpty() method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:
if (!k1.isEmpty()) {
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not. This also keeps you in track of total elements in the Array, You wont go out of Index.
if(k1 != null && k1.length != 0){
//Do something.
}
This is another way to do it...
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new Gson().toJson(response.body()));
JSONArray returnArray = jsonObject.getJSONArray("my_array");
// Do Work Only If Not Null
if (!returnArray.isNull(0)) {
for (int l = 0; l < returnArray.length(); l++) {
if (returnArray.length() > 0) {
// Get The Json Object
JSONObject returnJSONObject = returnArray.getJSONObject(l);
// Get Details
String imageUrl = returnJSONObject.optString("image");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
}
});

extracting Array data from SharedObject

Im having a game where after I finish a certain level I put that level`s name In an Array and save that array to an SharedObject(SO). But somehow/somewhere I mess up things, because after closing and opening the game again, I load the SO data (to unlock the levels that I have passed) and it is (the loaded data) always messed up and not loading what it should load(sometimes it even trows some errors at me.)
The code is not that difficult but I have been looking at it for far to long and I need new eyes to see the obvious mistakes in it.
***********EDIT**********
So the code for the SO is this
public class LevelsData extends SharedObject
{
public static var LEVELS_DATA:SharedObject = SharedObject.getLocal("save_poi71");
public static function get LoadNamesOfLevelPassed():Array
{
var myLevelsArr:Array = [];
if( LEVELS_DATA.data.PlayedLevels_arr == undefined)
{
myLevelsArr.length = 0;
}
else
{
myLevelsArr = LEVELS_DATA.data.PlayedLevels_arr;
}
return myLevelsArr;
}
public static function set SaveLevel_Names( nameOfLevelPassed:Array ):void
{
LEVELS_DATA.data.PlayedLevels_arr = nameOfLevelPassed;
LEVELS_DATA.flush();
}
}
and the code in the game is this
.
.
.
.
private function didWePlaySameLevel():void
{
var namesPlayed_arr:Array = LevelsData.LoadNamesOfLevelPassed;
var namesTotal:int = namesPlayed_arr.length;
if( namesTotal == 0 )
{
trace(" ScreenInGame_2 | didWePlaySameLevel | namesTotal == 0 so we push Level_1");
namesPlayed_arr.push( Moving_Picture_Name );
LevelsData.SaveLevel_Names = namesPlayed_arr;
sameLevel = false;
}
else if( namesTotal != 0 )
{
for( var i:int = 0; i < namesTotal; i++)
{
trace(" ScreenInGame_2 | didWePlaySameLevel | " + Moving_Picture_Name + " ?==? " + namesPlayed_arr[ i ] );
trace(" ScreenInGame_2 | didWePlaySameLevel | namesPlayed_arr.length = " + namesPlayed_arr.length);
if( Moving_Picture_Name != namesPlayed_arr[ i ] )
{
trace(" ScreenInGame_2 | didWePlaySameLevel | " + Moving_Picture_Name + " != " + namesPlayed_arr[ i ] );
namesPlayed_arr.push( Moving_Picture_Name );
LevelsData.SaveLevel_Names = namesPlayed_arr;
sameLevel = false;
trace(" ScreenInGame_2 | didWePlaySameLevel | namesPlayed_arr.length = " + namesPlayed_arr.length);
}
}
}
}
.
.
.
if( levelsToUnlock < totalLevels && sameLevel == false )
{
trace("ScreenInGame | unlockOneMoreLevel | we UNLOCK 1 more level" );
unlockNextLevel();
}
***EDIT PROBLEM:
SomeHow i figured a way of solving my 1st problem, but now there is a new one and that is :
When the Array from the SO is != 0 i go into the else if statement. There i compare if any of the variables in the Array have the same name of the Moving_Picture_Name and if they dont then I set the sameLevel = false. The problem is that, if lets say I have passed/played 5 levels before( Level_1,Level_2,Level_3,Level_4,Level_5 ) and lets say I start playing Level_2 again it would show me this:
Level_2 != Level_1 - > and it will push itself into the Array and update the data
Level_2 == Level_2 - > it will do nothing
Level_2 != Level_3 - > and it will push itself into the Array and update the data
Level_2 != Level_4 - > and it will push itself into the Array and update the data
Level_2 != Level_5 - > and it will push itself into the Array and update the data
so it will actually push 4 Elements in the Array that exist already in that Array.
***THE QUESTION :
So how do I push the newLevel only if its name isnt in that Array(the one where I save the names), And how do I do nothing if the name exist in the Array already.
You may have to convert your array to ByteArray, and save that. When you read it back, you will have to do the reverse operation. StackOverflow example link

counting occurrences in an array

I am trying to count the number of occurrences in an array of cart items in Magento.
There are several items in the array, all with a price field (either $0 and $10)
What I'm looking to do, is to display the count of those items that have a price of 0
I currently have:
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
echo 'Item is free';
}
else {
}
}
This simply outputs all the free items. Ideally, I'd like to display just the count of such items.
Could I use something like array_count_values, but limit it to only count those values that are 0?
You can do that with several ways, but having that code the most easy one will be:
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
$freeItems = 0;
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
$freeItems++;
}
}
echo "There are $freeItems free items";
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
$free = 0;
$notfree = 0;
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
echo 'Item is free';
$free++;
}
else {
$notfree++;
}
}
echo 'total free items = ' . $free;
echo 'total nonfree items = ' . $notfree;

Resources