rearranging an array of data without using temporary array - arrays

How can I rearrange an array if I know where to put each element in array without using temporary array?
I guess, This has something to do with cyclic permutation but I cannot figure out how they can be linked each other. Wiki page seems irrelevant to me(http://en.wikipedia.org/wiki/Cyclic_permutation)

If you know both where to put each element in the array, and also which element of the array belongs at a specific index, then you can use that information to optimise your rearrangement. Otherwise you can iterate over all the array elements exchanging them into the correct location until they are all correctly placed.
void permuteObjects(Object[] elements, int[] positions)
{
for (int i = 0; i < elements.length; ++i) {
while (positions[i] != i) {
swapObjects(elements, i, positions[i]);
swapIntegers(positions, i, positions[i]);
}
}
}

If you can boil down the "re-arrangement" of your array to single permutations, i.e. to swapping the values of two elements then you can use the XOR to perform the swap without additional variable.
Here a sample code from the linked Wikipedia article:
void xorSwap (int *x, int *y) {
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}

Why not just use a temporary array and terminate it by setting it to null?
Maybe take a look at http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
HashMaps dynamicly increase when adding new items.
Use like this:
HashMap<Integer, WhatEverYouWantToStore> = new HashMap<Integer, WhatEverYouWantToStore>();

Maybe try this:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class sort {
        public static void main(String[] args) {
                List list = new ArrayList();
                String country[] = { "India", "Japan", "USA", "UK", "Nepal" };
                for (int i = 0; i < 5; i++) {
                        list.add(country[i]);
                }
                Collections.sort(list);
                Iterator i = list.iterator();
                while (i.hasNext()) {
                        System.out.print(i.next() + "\t");
                }
        }
}

Related

how to use long options in c?

how to use long options via getopt_long:
for example like this:
--wide-option
I have --wide and -w.
And on --wide-option it gives the following error:
"unrecognized option"
int main(int argc, char **argv)
{
    struct option opts[] =
    {
        {"wide", 1, 0, 'w'},
        {
            0, 0, 0, 0
        }
    };
    int option_val = 0;
    int counter = 10;
    int opindex = 0;
    while ((option_val = getopt_long(argc, argv, "w:", opts, &opindex)) != -1)
    {
        switch (option_val)
        {
        case 'w':
            if (optarg != NULL)
                counter = atoi(optarg);
            for (int i = 0; i < counter; i++)
                printf("Hello world\n");
            break;
        default:
            return 0;
        }
    }
    return 0;
}
If you look at the cat source code (here), you can see that --number and --number-nonblank are two different options (-b and -n). (near line 555).
If you want to do the same, you can that way:
#include <getopt.h>
#include <stdio.h>
int main(int argc, char **argv)
{
struct option opts[] =
{
{"wide", 1, 0, 'w'},
{"wide-option", 0, 0, 'o'}, /* declare long opt here */
{
0, 0, 0, 0
}
};
int option_val = 0;
int counter = 10;
int opindex = 0;
while ((option_val = getopt_long(argc, argv, "w:o", opts, &opindex)) != -1) /* the case here (I arbitrary choose 'o') */
{
switch (option_val)
{
case 'w':
if (optarg != NULL)
counter = atoi(optarg);
printf("option --wide %d found!\n", counter);
for (int i = 0; i < counter; i++)
printf("Hello world\n");
break;
case 'o': /* and take the case into account */
printf("option --wide-option found!\n");
break;
default:
return 0;
}
}
return 0;
}

User defined functions in c are not switching

problem
I was making a c program in which users details are accepted checked and added to a file
but while compile the functions are not changing i meant it only asks the name and the program end
can someone please help me out!
#include <string.h>
void main()
void regis_name();
void regis_dob();
void regis_pin();
void check();
//checks code is not added here
{
     int a, i, j, n, b, f = 1, d[1], m[1], y[1], f1 = 1;
    int *a1, *d1[1], *m1[1], *y1[1];
    a1 = a;
    d1[1] = &d[1];
    m1[1] = &m[1];
    y1[1] = &y[1];
    regis_pin();
void regis_name()
{
    char name[3];
    printf("ADD YOUR NAME: \n ");
    scanf("%s", name[3]);
   regis_dob(); // to dob
}
bd
void regis_dob()
{
    int a, i, j, n, b, f = 1, d[1], m[1], y[1], f1 = 1;
    printf("enter date in 'dd' month in 'mm' year in 'yyyy' \n \n");
    printf("enter dd:   \n");
    scanf("%d", &d[1]);
    printf("enter mm:   \n");
    scanf("%d", &m[1]);
    printf("enter yyyy:  \n");
    scanf("%d", &y[1]);
   regis_pin; // to pin
}
void regis_pin()
{
    int a;
    printf("ADD A PASS CODE OF 4 DIGIT:  \n");
    scanf("%d", &a);
    printf("\n");
    check(); // to pin check
}```

How do I sort a doubly-linked list in ascending order?

I am trying to perform an insertion-sort function on a doubly linked list in the C programming language. When I run the code with this function on a doubly linked list of
1<-->3<-->7<-->4<-->9 I get a sorted output. However, When I run this code on a doubly linked list of 5<-->3<-->7<-->4<-->9 I get a blank output (and yes it still compiles and runs).
I cannot figure out why it is returning a blank output when the first node has greater value than the second. I would guess it has something to do with my if statement?
void insertion_sort_increasing(struct List *list)
{
  struct Node *current_node = list->head; //initialize current_node
  struct Node *tempA;
  struct Node *tempB;
  struct Node *tempC;
  struct Node *tempD;
  if (current_node == NULL) {
      printf("Empty List.");
  } else {
      current_node = current_node->next;
      while (current_node != NULL) { //iterates doubly linked list
          if (current_node->prev->StudentID > current_node->StudentID) {
              tempA = current_node; //(3 in this case)
              tempB = current_node->prev->prev; //(NULL in this case)
              tempC = tempA->next->prev;
              tempD = tempB->next;
              tempA->next->prev = tempA->prev; // 5<--7
              tempB->next->prev = tempC; // 3<--5
              tempB->next = tempA->prev->next; // NULL-->3
              tempA->prev->next = tempA->next; // 5-->7
              tempA->next = tempD; // 3-->5
              tempA->prev = tempD->prev; // NULL<--3
              if (tempB == NULL) {
                  list->head = tempB->next; // 3 = head
              }
          }
          current_node = current_node->next;
      }
  }
}
There are multiple problems in your code:
you perform a single scan through the list, swapping adjacent nodes that are out of order. This loop does not handle the case of a node that should move left by more than one position.
the code crashes if tempB is null, ie: if the 2 initial nodes of the list should be swapped.
list->head should be updated if the first node changes.
the temporary variable names are confusing, esp tempC that is equal to tempA, and the initial order is not tempA -> tempB -> tempC -> tempD.
for insertion sort, you should move the current node to its position among the nodes sorted so far and skip to the next node until you reach the end of the list.
Here is a modified version:
void insertion_sort_increasing(struct List *list)
{
struct Node *current_node = list->head;
while (current_node != NULL) {
struct Node *next = current_node->next;
while (current_node->prev && current_node->prev->StudentID > current_node->StudentID) {
// swap current_node and its predecessor (tempC and tempB)
struct Node *tempA = current_node->prev->prev;
struct Node *tempB = current_node->prev;
struct Node *tempC = current_node;
struct Node *tempD = current_node->next;
if (tempA) {
tempA->next = tempC;
} else {
list->head = tempC;
}
tempC->prev = tempA;
tempC->next = tempB;
tempB->prev = tempC;
tempB->next = tempD;
if (tempD) {
tempD->prev = tempB;
} else {
list->tail = tempB;
}
}
current_node = next;
}
}
You need to learn to separate concerns in your code. An insertion sort takes an input list or array and returns an output list or array. So to start with, you need a function that either takes a List** and returns void, or it takes a List* and returns a List*. Logically you need to do three things correctly, 1) iterate over the input list, 2) Remove a node from the input list without breaking 1, 3) insert into the output list at the correct position for the sort order. That amounts to three functions.
List *InsertionSort(List * pList) {...}
List *SortedInsert(List *pList, List *pNode) {...}
List *Remove(List *pNode) {...}
InsertionSort just loops over the it's input, calling Remove, without loosing track of the head or tail pointer, depending on which way you're moving through the list, and then calls SortedInsert with the node it just removed from the head or tail of the pList. SortedInsert then iterates through pList looking for the correct place to insert pNode and then returns the new head of the list, which might just be pNode.
It's just easier to think about one operation at a time, and the code you write will be simpler and easier to understand and debug. In fact, you can test SortedInsert first, to make sure it's working, then test Remove, and then move on to to InsertionSort. You'll need to learn how to use your debugger and make yourself familiar with stepping through your code and checking the state of your variables. A fourth function, PrintList is probably on order here as well.
I am not going to write a bunch of code or be really explicit about the algorithm details, because you can get that with an SO or Google search, and this seems like an obvious homework assignment.

LUA file reading

I am modding a game script where I can locate something in my minimap by getting the specific x,y coordinates. For that, I made a file that stores those values like this :
LocationName
X position
Y position
So, I came out with that code to read them
for line in file:lines() do
            if string.find(line, Location) then
                var1 = file:read("*line")
                var2= ??????????????
            end
        end
The X position can be easily read using the read("*line"), But how am I supposed to read the Y position that is underneath?
This works fine:
var1 = file:read("*line")
var2 = file:read("*line")

Strtok:I dont know why this program keeps failing

In this program the char *token is initialized with a weird garbage value.I am unable to sort it out. Here's the source code:
#include<iostream>
#include<string.h>
#include<stdlib.h>
void fetch_value(char *string,int pos,char *dest)
{
    char *token;
    int i=0;
    token=strtok(string,",");
    if(pos>1)
    {
        token=strtok(NULL,",");
        while(i<pos-1){
            token=strtok(NULL,",");
            printf("token =%s\n",token);
            i++;
        }
        strcpy(dest,token);
    }
    else
    {
        strcpy(dest,token);
    }
}
int main(void)
{
    char checking[100];
    memset(checking,0x00,sizeof(checking));
    fetch_value("14174000100,35679700322,35679700322,35679700322,
            35679700322,14174000999,919440710210000,1",0,checking);
    printf("checking=%s\n",checking);
    return 0;
}
Your help, feedback or suggestions is greatly appreciated.
The first argument of strtok must be modifiable. Your code passes a string literal, which is not modifiable. This leads to undefined behavior.
The simplest modification that will fix the problem is as follows:
char numList[] = "14174000100,35679700322,35679700322,35679700322,35679700322,14174000999,919440710210000,1";
fetch_value(numList, 0, checking);
You should also note that strtok is an older function which is not reentrant, because it uses static variables to save its state. In the new code you should use the reentrant version of the function - strtok_r, which requires you to pass memory for saving the state.
Do this instead:
int main(void)
{
char checking[100];
memset(checking,0x00,sizeof(checking));
char string[] = "14174000100,35679700322,35679700322,35679700322,
35679700322,14174000999,919440710210000,1";
//now string can be modified.
fetch_value(&string[0],0,checking);
printf("checking=%s\n",checking);
return 0;
}

Resources